利用一個(gè)例子千贯,我們初步理解了python GUI編程PyQt5庫(kù)的使用流程。接下來(lái)搞坝,我將會(huì)系統(tǒng)的整理下關(guān)于pyqt的學(xué)習(xí)筆記搔谴,方便以后查閱。
1. 整體框架
一個(gè)pyqt5程序桩撮,都有一個(gè)框架敦第,包括初始化控件、布局設(shè)置店量、命名芜果、設(shè)計(jì)導(dǎo)入樣式融师、程序功能邏輯、程序顯示及退出等等旱爆。在了解此框架的基礎(chǔ)上,我們?cè)倮^續(xù)學(xué)習(xí)其中的細(xì)節(jié)疼鸟,完善自己的程序。
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication,QWidget
import sys
# 這里是基于QWidget類浩淘,也可以基于QMainWindow吴攒,甚至其他控件,需要什么類型的就基于什么父類
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI() # 界面繪制交給InitUi方法
self.initLayout() # 界面布局交給initLayout方法
self.initName() # 命名控件交給initName方法
self.setStyleSheet("") # 設(shè)置樣式
self.function()
def initUI(self):
pass
def initLayout(self):
pass
def initName(self):
pass
def function(self):
pass
if __name__=="__main__":
# 創(chuàng)建應(yīng)用程序和對(duì)象
app = QApplication(sys.argv)
window = Example()
window.show() # 顯示窗口
sys.exit(app.exec_())
在上面的基本框架中,我們接下來(lái)會(huì)加入一些常用的基本功能镣隶,如應(yīng)用程序圖標(biāo)诡右、顯示提示語(yǔ)帆吻、關(guān)閉窗口按鈕……等
2. 應(yīng)用程序相關(guān)
# 絕對(duì)定位咙边,設(shè)置窗口的位置和大小,前兩位是程序左上角的位置,后兩位是程序的寬高
self.setGeometry(300, 300, 300, 220)
# 窗體大小
self.resize(300,200)
# 設(shè)置窗口的標(biāo)題
self.setWindowTitle('PyQt5')
# 設(shè)置窗口的圖標(biāo)王带,引用當(dāng)前目錄下的1.png圖片
self.setWindowIcon(QIcon('1.png'))
3. 顯示提示工具QToolTip
from PyQt5.QtWidgets import QToolTip,
# 設(shè)置一個(gè)用于顯示工具提示的字體市殷。我們使用10px滑體字體。
QToolTip.setFont(QFont('SansSerif', 10))
# 創(chuàng)建一個(gè)提示盟戏,我們稱之為settooltip()方法甥桂。我們可以使用豐富的文本格式(富文本格式)
self.setToolTip('This is a <b>QWidget</b> widget')
# 創(chuàng)建一個(gè)PushButton并為他設(shè)置一個(gè)tooltip
btn = QPushButton('Button', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')
4. 關(guān)閉窗口按鈕
from PyQt5.QtCore import QCoreApplication
qbtn = QPushButton('Quit', self)
qbtn.clicked.connect(QCoreApplication.instance().quit)
5. 消息框QMessageBox
下面這個(gè)程序集合了六種消息框邮旷,大家在使用時(shí)可以直接改寫成自己需要的形式婶肩,其中按鈕的ok/cancel如果想要改成中文,需要其他語(yǔ)句添加改寫按鈕律歼,大家可自行百度险毁。
# QMessageBox.information 信息框
# QMessageBox.question 問(wèn)答框
# QMessageBox.warning 警告
# QMessageBox.ctitical 危險(xiǎn)
# QMessageBox.about 關(guān)于
# QMessageBox.aboutQt 關(guān)于QT
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QMessageBox, QGridLayout, QLabel, QPushButton, QFrame
class MessageBox(QWidget):
def __init__(self):
super(MessageBox,self).__init__()
self.initUi()
def initUi(self):
self.setWindowTitle("MessageBox")
self.setGeometry(400,400,300,290)
self.questionLabel = QLabel("Question:")
self.questionLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self.infoLabel = QLabel("Information:")
self.infoLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self.warningLabel = QLabel("Warning:")
self.warningLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self.criticalLabel = QLabel("Critical:")
self.criticalLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self.aboutLabel = QLabel("About:")
self.aboutLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self.aboutQtLabel = QLabel("About QT:")
self.aboutQtLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self.resultLabel = QLabel("Result:")
self.resultLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
questButton = QPushButton("...")
questButton.clicked.connect(self.selectQuestion)
infoButton = QPushButton("...")
infoButton.clicked.connect(self.selectInfo)
warningButton = QPushButton("...")
warningButton.clicked.connect(self.selectWarning)
criticalButton = QPushButton("...")
criticalButton.clicked.connect(self.selectCritical)
aboutButton = QPushButton("...")
aboutButton.clicked.connect(self.selectAbout)
aboutQtButton = QPushButton("...")
aboutQtButton.clicked.connect(self.selectAboutQt)
mainLayout = QGridLayout()
mainLayout.addWidget(self.questionLabel, 0, 0)
mainLayout.addWidget(questButton, 0, 1)
mainLayout.addWidget(self.infoLabel, 1, 0)
mainLayout.addWidget(infoButton, 1, 1)
mainLayout.addWidget(self.warningLabel, 2, 0)
mainLayout.addWidget(warningButton, 2, 1)
mainLayout.addWidget(self.criticalLabel, 3, 0)
mainLayout.addWidget(criticalButton, 3, 1)
mainLayout.addWidget(self.aboutLabel, 4, 0)
mainLayout.addWidget(aboutButton, 4, 1)
mainLayout.addWidget(self.aboutQtLabel, 5, 0)
mainLayout.addWidget(aboutQtButton, 5, 1)
mainLayout.addWidget(self.resultLabel, 6, 1)
self.setLayout(mainLayout)
def selectQuestion(self):
button = QMessageBox.question(self, "Question", "檢測(cè)到程序有更新鲸鹦,是否安裝最新版本跷跪?", QMessageBox.Ok | QMessageBox.Cancel,
QMessageBox.Ok)
if button == QMessageBox.Ok:
self.resultLabel.setText("<h2>Question:<font color=red> OK</font></h2>")
elif button == QMessageBox.Cancel:
self.resultLabel.setText("<h2>Question:<font color=red> Cancel</font></h2>")
else:
return
def selectInfo(self):
QMessageBox.information(self, "Information", "程序當(dāng)前版本為V3.11")
self.resultLabel.setText("Information")
def selectWarning(self):
button = QMessageBox.warning(self, "Warning", "恢復(fù)出廠設(shè)置將導(dǎo)致用戶數(shù)據(jù)丟失,是否繼續(xù)操作葛菇?",
QMessageBox.Reset | QMessageBox.Help | QMessageBox.Cancel, QMessageBox.Reset)
if button == QMessageBox.Reset:
self.resultLabel.setText("<h2>Warning:<font color=red> Reset</font></h2>")
elif button == QMessageBox.Help:
self.resultLabel.setText("<h2>Warning:<font color=red> Help</font></h2>")
elif button == QMessageBox.Cancel:
self.resultLabel.setText("<h2>Warning:<font color=red> Cancel</font></h2>")
else:
return
def selectCritical(self):
QMessageBox.critical(self, "Critical", "服務(wù)器宕機(jī)眯停!")
self.resultLabel.setText("<h2><font color=red>Critical</font></h2>")
def selectAbout(self):
QMessageBox.about(self, "About", "Copyright 2015 Tony zhu.\n All Right reserved.")
self.resultLabel.setText("About")
def selectAboutQt(self):
QMessageBox.aboutQt(self, "About Qt")
self.resultLabel.setText("About Qt")
if __name__=="__main__":
import sys
app=QApplication(sys.argv)
myshow=MessageBox()
myshow.show()
sys.exit(app.exec_())
再來(lái)看一個(gè)常用的關(guān)閉窗口提示,改寫了自帶的closeEvent方法吗冤,如下:
def closeEvent(self, event):
reply = QMessageBox.question(self, 'Message',
"Are you sure to quit?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
6. 窗口顯示在屏幕中間
from PyQt5.QtWidgets import QDesktopWidget
self.center()
def center(self):
# 獲得窗口
qr = self.frameGeometry()
# 獲得屏幕中心點(diǎn)
cp = QDesktopWidget().availableGeometry().center()
# 顯示到屏幕中心
qr.moveCenter(cp)
self.move(qr.topLeft())