PyQt5--基础

#-*-coding:utf-8 -*-

PyQt5是由一系列Python模块组成。超过620个类,6000函数和方法。能在诸如Unix、Windows和Mac
OS等主流操作系统上运行。PyQt5有两种证书,GPL和商业证书。

PyQt5类分为很多模块,主要模块有:

- QtCore 包含了核心的非GUI的功能。主要和时间、文件与文件夹、
各种数据、流、URLs、mime类文件、进程与线程一起使用。
- QtGui 包含了窗口系统、事件处理、2D图像、基本绘画、字体和文字类。

QtWidgets类包含了一系列创建桌面应用的UI元素。
QtMultimedia包含了处理多媒体的内容和调用摄像头API的类。
QtBluetooth模块包含了查找和连接蓝牙的类。
QtNetwork包含了网络编程的类,这些工具能让TCP/IP和UDP开发变得更加方便和可靠。
QtPositioning包含了定位的类,可以使用卫星、WiFi甚至文本。
Engine包含了通过客户端进入和管理Qt Cloud的类。
QtWebSockets包含了WebSocket协议的类。
QtWebKit包含了一个基WebKit2的web浏览器。
QtWebKitWidgets包含了基于QtWidgets的WebKit1的类。
QtXml包含了处理xml的类,提供了SAX和DOM API的工具。
QtSvg提供了显示SVG内容的类,Scalable Vector Graphics (SVG)是一种是一种基于可扩展标记语言(XML),
用于描述二维矢量图形的图形格式(这句话来自于维基百科)。
QtSql提供了处理数据库的工具。
QtTest提供了测试PyQt5应用的工具。

Perl,Python,和Ruby都是使用最广泛的脚本语言,它们有很多共同的特点,也是相互的竞争对手。

import sys
from PyQt5.QtWidgets import QApplication,QWidget,QLabel
from PyQt5.QtWidgets import QMainWindow,QAction,qApp
from PyQt5.QtGui import QIcon,QColor
from PyQt5.QtWidgets import QPushButton,QHBoxLayout,QVBoxLayout
from PyQt5.QtWidgets import QLineEdit, QTextEdit,QGridLayout
from PyQt5.QtWidgets import QInputDialog,QFrame,QColorDialog
from PyQt5.QtWidgets import QSizePolicy,QFontDialog
from PyQt5.QtWidgets import QFileDialog

app = QApplication(sys.argv)
#每个PyQt5应用都必须创建一个应用对象。sys.argv是一组命令行参数的列表。Python可以在shell里运行,
这个参数提供对脚本控制的功能。
w = QWidget()
w.resize(250,150)
w.move(300,30)
w.setWindowTitle("selen")
w.show()
#应用的主循环中,事件处理器这个时候开始工作。
sys.exit(app.exec_())


from PyQt5.QtGui import QIcon

class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI() #调用方法
def initUI(self):
self.setGeometry(300,300,300,220)
# resize() and move() x,y,w,h
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('./web.png'))

self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
print(sys.argv)
ex = Example()
sys.exit(app.exec_())


class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
QToolTip.setFont(QFont('SanSerif',20))
#提示框 字体
self.setToolTip('This is a <b>QWdget</b> widget')
#窗体的提示 QPushButton(string text,QwWidget parent = None)
btn = QPushButton('selen',self)
# 加黑加粗
btn.setToolTip('This is a <b>QPushButton</b> widget')
# 按钮的提示
btn.resize(btn.sizeHint())
btn.move(50,50)

self.setGeometry(300,300,300,300)
self.setWindowTitle("Tooltips")
self.show()

from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QCoreApplication
#程序需要`QtCore`对象
class Example(QWidget):

def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
qbtn = QPushButton('clicked',self)
qbtn.clicked.connect(QCoreApplication.instance().quit)
#事件传递系统在PyQt5内建的singleslot机制里面。点击按钮之后,
# 信号会被捕捉并给出既定的反应。
# `QCoreApplication`包含了事件的主循环,它能添加和删除所有的事件,
# `instance()`创建了一个它的实例。`QCoreApplication`是在`QApplication`里创建的。
# 点击事件和能终止进程并退出应用的quit函数绑定在了一起。
# 在发送者和接受者之间建立了通讯,发送者就是按钮,接受者就是应用对象。
qbtn.resize(qbtn.sizeHint())
#PyQt5.QtCore.QSize(80, 28)
print(qbtn.sizeHint())

qbtn.move(150,100)

self.setGeometry(300,300,250,150)
self.setWindowTitle("selen")
self.show()

from PyQt5.QtWidgets import QMessageBox
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):

self.setGeometry(300,300,300,300)
self.setWindowTitle("MessageBox")
self.show()
def closeEvent(self,event):
reply = QMessageBox.question(self,'Message',
'Are you sure to quit?',
QMessageBox.Yes | QMessageBox.No,
QMessageBox.Yes)
#第一个字符串显示在消息框的标题栏,第二个字符串显示在对话框,
#第三个参数是消息框的俩按钮,最后一个参数是默认按钮,这个按钮是默认选中的。
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()



from PyQt5.QtWidgets import QDesktopWidget
#QDesktopWidget提供了用户的桌面信息
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.resize(250,150)
self.center()

self.setWindowTitle('Center')
self.show()
def center(self):
#获得主窗口所在的框架
qr = self.frameGeometry()
#获取显示器的分辨率,然后得到屏幕中间点的位置。
cp = QDesktopWidget().availableGeometry().center()
#然后把主窗口框架的中心点放置到屏幕的中心位置。
qr.moveCenter(cp)
#然后通过move函数把主窗口的左上角移动到其框架
# 的左上角,这样就把窗口居中了
self.move(qr.topLeft())

from PyQt5.QtWidgets import QMainWindow

class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#状态栏
self.statusBar().showMessage("Ready")
self.setGeometry(300,300,250,150)
self.setWindowTitle("Statusbar")
self.show()

from PyQt5.QtWidgets import QMainWindow,QAction,qApp
from PyQt5.QtGui import QIcon

class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#行为
exitAct = QAction(QIcon('exit.png'),'&Exit',self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit application')
exitAct.triggered.connect(qApp.quit)

self.statusBar()
#菜单栏
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAct)

self.setGeometry(300,300,300,300)
self.setWindowTitle('selen')
self.show()



from PyQt5.QtWidgets import QMenu

class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#创建一个菜单栏

menubar = self.menuBar()
filemenu = menubar.addMenu('Flie')
#子菜单
impMenu = QMenu('Import',self)
impAct = QAction('Import mail',self)
impMenu.addAction(impAct)

newAct = QAction('New',self)
filemenu.addAction(newAct)
filemenu.addMenu(impMenu)

self.setGeometry(300,300,300,200)
self.setWindowTitle('Submenu')
self.show()



class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()

def initUI(self):

self.statusBar = self.statusBar()
self.statusBar.showMessage('Ready')
#菜单栏
menubar = self.menuBar()
#添加并创建一个menu
viewMenu = menubar.addMenu('view')

viewStatuAct = QAction('view status',self,checkable = True)
viewStatuAct.setStatusTip('view statusbar')
viewStatuAct.setChecked(True)
viewStatuAct.triggered.connect(self.toggleMenu)

viewMenu.addAction(viewStatuAct)

self.setGeometry(300,300,300,300)
self.setWindowTitle('Check menu')
self.show()

def toggleMenu(self,state):
if state:
self.statusBar.show()
#state = False
else:
self.statusBar.hide()
#state = True

from PyQt5.QtWidgets import QMenu


class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):

self.setGeometry(300,300,300,300)
self.setWindowTitle('Context menu')
self.show()
#鼠标右健
def contextMenuEvent(self, event):
cmenu = QMenu(self)
newAct = cmenu.addAction('New')
openAct = cmenu.addAction('Open')
quitAct = cmenu.addAction("Quit")
#把菜单位置移动到鼠标位置
action = cmenu.exec_(self.mapToGlobal(event.pos()))

if action == quitAct:
qApp.quit()
if action == newAct:
print('new')



class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#action
exitAct = QAction(QIcon('exit.png'),'Exit',self)
exitAct.setShortcut('Ctrl+Q')
exitAct.triggered.connect(qApp.quit)
# 可添加和删除 栏 菜单
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAct)

self.setGeometry(200,200,200,200)
self.setWindowTitle('ToolBar')
self.show()

from PyQt5.QtWidgets import QTextEdit
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#文本编辑框
textEdit = QTextEdit()
self.setCentralWidget(textEdit)
# 创建一个action
exitAct = QAction(QIcon('exit.png'),'exit',self)
exitAct.setShortcut('Ctrl+Q')
#可以设置状态栏
exitAct.setStatusTip('Exit application')
exitAct.triggered.connect(self.close)

self.statusBar()

menubar = self.menuBar()
filemenu = menubar.addMenu('&File')
filemenu.addAction(exitAct)

toolbar = self.addToolBar('Exit')
toolbar.addAction(exitAct)

self.setGeometry(300,300,300,300)
self.setWindowTitle('Main window')
self.show()


class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):

lab1 = QLabel('Zetcode',self)
lab1.move(15,10)

lab2 = QLabel('tutorial',self)
lab2.move(35,40)

lab3 = QLabel('for program',self)
lab3.move(55,70)

self.setGeometry(300,300,300,300)
self.setWindowTitle('Absolute')
self.show()

class Example(QWidget):
def __init__(self):
super().__init__()

self.initUI()
def initUI(self):
okButton = QPushButton('Ok')
cancelButton = QPushButton("Cancel")

hbox = QHBoxLayout()
# 用弹簧把按钮布置在右下方
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)

vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)

self.setLayout(vbox)

self.setGeometry(300,300,300,300)
self.setWindowTitle('Buttons')
self.show()

class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
title = QLabel('Title')
author = QLabel('Author')
review = QLabel('Review')

titleEdit = QLineEdit()
authorEdit = QLineEdit()
reviewEdit = QTextEdit()

grid = QGridLayout()
grid.setSpacing(10)

grid.addWidget(title,1,0)
grid.addWidget(titleEdit,1,1)

grid.addWidget(author,2,0)
grid.addWidget(authorEdit,2,1)

grid.addWidget(review,3,0)
grid.addWidget(reviewEdit,3,1,5,1)

self.setLayout(grid)

self.setGeometry(300,300,300,300)
self.setWindowTitle('Review')
self.show()

class Example(QWidget):
def __init__(self):
super().__init__()

self.initUI()
def initUI(self):
self.bn = QPushButton('Dialog',self)
self.bn.move(20,20)
# 连接信号
self.bn.clicked.connect(self.showDialog)
#方法间的 self变量可以通用
self.le = QLineEdit(self)
self.le.move(130,20)

self.setGeometry(300,300,300,300)
self.setWindowTitle("Input Dialog")

self.show()

def showDialog(self):
#返回两个值 一个是文本内容 一个

text, ok = QInputDialog.getText(self,'input Dialog',
'Entry your name:')
if ok:
self.le.setText(str(text))

class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
col = QColor(0,0,0)

self.btn = QPushButton('Dialog',self)
self.btn.move(20,20)
self.btn.clicked.connect(self.showDialog)
#控制一些边框样式:例如:凸起、凹下、阴影、线宽
self.frm = QFrame(self)
self.frm.setStyleSheet("QWidget { ">130,22,100,100)

self.setGeometry(300,300,250,180)
self.setWindowTitle('Color dialog')
self.show()

def showDialog(self):
col = QColorDialog.getColor()
if col.isValid():
self.frm.setStyleSheet('QWidget { ">class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
vbox = QVBoxLayout()

btn = QPushButton('Dialog',self)
btn.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
btn.move(20,20)
btn.clicked.connect(self.showDialog)

vbox.addWidget(btn)

self.lbl = QLabel('Knowledge only matters',self)
self.lbl.move(130,20)

vbox.addWidget(self.lbl)

self.setLayout(vbox)
self.setGeometry(300,300,300,300)
self.setWindowTitle('Color Dialog')
self.show()

def showDialog(self):
front, ok = QFontDialog.getFont()
if ok:
self.lbl.setFont(front)


class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):

self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.statusBar()
#创建一个ieaction
openfile = QAction(QIcon('exit.png'),'Open',self)
openfile.setShortcut('Ctrl+O')
openfile.setStatusTip('Open new file')
#创建连接
openfile.triggered.connect(self.showDialog)

menubar = self.menuBar()
filemenu = menubar.addMenu('&File')
#添加action到菜单
filemenu.addAction(openfile)

self.setGeometry(300,300,300,300)
self.setWindowTitle('File dialog')
self.show()

def showDialog(self):
#('/home/selen/qt支持中文.txt', 'All Files (*)')
fname = QFileDialog.getOpenFileName(self,'Open file','/home/selen')
print(fname)
if fname[0]:
f = open(fname[0],'r')
with f:
data = f.read()
self.textEdit.setText(data)

if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
sys.exit(app.exec_())

原文地址:https://www.cnblogs.com/countryboy666/p/11185670.html