PyQt基础学习(一)

利用一个例子,我们初步理解了python GUI编程PyQt5库的使用流程。接下来,我将会系统的整理下关于pyqt的学习笔记,方便以后查阅。

1. 整体框架

一个pyqt5程序,都有一个框架,包括初始化控件、布局设置、命名、设计导入样式、程序功能逻辑、程序显示及退出等等。在了解此框架的基础上,我们再继续学习其中的细节,完善自己的程序。

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("") # 设置样式
        self.function()

    def initUI(self):
        pass

    def initLayout(self):
        pass

    def initName(self):
        pass

    def function(self):
        pass

if __name__=="__main__":
    # 创建应用程序和对象
    app = QApplication(sys.argv)
    window = Example()
    window.show() # 显示窗口
    sys.exit(app.exec_())


在上面的基本框架中,我们接下来会加入一些常用的基本功能,如应用程序图标显示提示语关闭窗口按钮……等

2. 应用程序相关

# 绝对定位,设置窗口的位置和大小,前两位是程序左上角的位置,后两位是程序的宽高
self.setGeometry(300, 300, 300, 220)
# 窗体大小
self.resize(300,200)
# 设置窗口的标题
self.setWindowTitle('PyQt5')
# 设置窗口的图标,引用当前目录下的1.png图片
self.setWindowIcon(QIcon('1.png'))

3. 显示提示工具QToolTip

from PyQt5.QtWidgets import QToolTip,
# 设置一个用于显示工具提示的字体。我们使用10px滑体字体。
QToolTip.setFont(QFont('SansSerif', 10))
# 创建一个提示,我们称之为settooltip()方法。我们可以使用丰富的文本格式(富文本格式)
self.setToolTip('This is a QWidget widget')
# 创建一个PushButton并为他设置一个tooltip
btn = QPushButton('Button', self)
btn.setToolTip('This is a QPushButton widget')

4. 关闭窗口按钮

from PyQt5.QtCore import QCoreApplication

qbtn = QPushButton('Quit', self)
qbtn.clicked.connect(QCoreApplication.instance().quit)

5. 消息框QMessageBox

下面这个程序集合了六种消息框,大家在使用时可以直接改写成自己需要的形式,其中按钮的ok/cancel如果想要改成中文,需要其他语句添加改写按钮,大家可自行百度。

# QMessageBox.information 信息框
# QMessageBox.question 问答框
# QMessageBox.warning 警告
# QMessageBox.ctitical 危险
# QMessageBox.about 关于
# QMessageBox.aboutQt 关于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", "检测到程序有更新,是否安装最新版本?", QMessageBox.Ok | QMessageBox.Cancel,
                                      QMessageBox.Ok)
        if button == QMessageBox.Ok:
            self.resultLabel.setText("

Question: OK

") elif button == QMessageBox.Cancel: self.resultLabel.setText("

Question: Cancel

") else: return def selectInfo(self): QMessageBox.information(self, "Information", "程序当前版本为V3.11") self.resultLabel.setText("Information") def selectWarning(self): button = QMessageBox.warning(self, "Warning", "恢复出厂设置将导致用户数据丢失,是否继续操作?", QMessageBox.Reset | QMessageBox.Help | QMessageBox.Cancel, QMessageBox.Reset) if button == QMessageBox.Reset: self.resultLabel.setText("

Warning: Reset

") elif button == QMessageBox.Help: self.resultLabel.setText("

Warning: Help

") elif button == QMessageBox.Cancel: self.resultLabel.setText("

Warning: Cancel

") else: return def selectCritical(self): QMessageBox.critical(self, "Critical", "服务器宕机!") self.resultLabel.setText("

Critical

") 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_())

再来看一个常用的关闭窗口提示,改写了自带的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()
        # 获得屏幕中心点
        cp = QDesktopWidget().availableGeometry().center()
        # 显示到屏幕中心
        qr.moveCenter(cp)
        self.move(qr.topLeft())

你可能感兴趣的:(PyQt基础学习(一))