PyQt5学习笔记(1)PyQt5简介,基本功能,布局管理

笔记内容参考:PyQt5 教程, 该文档翻译自PyQt5 tutorial

PyQt5安装参考: PyQt5的安装配置

PyQt5简介

PyQt5有620多个类和6000个函数和方法.

pyqt5的类别分为几个模块,包括以下:

  • QtCore:包含了核心的非GUI功能。此模块用于处理时间、文件和目录、各种数据类型、流、URL、MIME类型、线程或进程。
  • QtGui:包含类窗口系统集成、事件处理、二维图形、基本成像、字体和文本。
  • QtWidgets:包含创造经典桌面风格的用户界面提供了一套UI元素的类。
  • QtNetwork:包含了网络编程的类。这些类便于TCP和IP和UDP客户端和服务器的编码,使网络编程更容易和更便携。
  • QtWebSockets:包含实现WebSocket协议类。
  • QtWebKit:包含一个基于Webkit2图书馆Web浏览器实现类。
  • QtWebKitWidgets:含的类的基础webkit1一用于qtwidgets应用Web浏览器的实现。
  • QtSvg:提供了显示SVG文件内容的类。可伸缩矢量图形(SVG)是一种描述二维图形和图形应用的语言。
  • QtSql:提供操作数据库的类。
  • QtTest:单元测试等

可能使用不多的类:

  • QtMultimedia:含的类来处理多媒体内容和API来访问相机和收音机的功能。
  • QtBluetooth:扫描设备和连接并与他们互动。
  • QtPositioning:利用各种可能的来源,确定位置,包括卫星、Wi-Fi、或一个文本文件。
  • Enginio:实现了客户端库访问Qt云服务托管的应用程序运行时。
  • QtXml:包含与XML文件的类。这个模块为SAX和DOM API提供了实现。

PyQt5基本功能

示例1:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

# 这里我们提供必要的引用。基本控件位于pyqt5.qtwidgets模块中。
# 引用了 应用类,界面类 的两个基本类型
from PyQt5.QtWidgets import QApplication, QWidget


if __name__ == '__main__':
    #每一pyqt5应用程序必须创建一个应用程序对象。sys.argv参数是一个列表,从命令行输入参数。
    app = QApplication(sys.argv)
    #QWidget部件是pyqt5所有用户界面对象的基类。他为QWidget提供默认构造函数。默认构造函数没有父类。
    w = QWidget()
    #resize()方法调整窗口的大小。这离是250px宽150px高
    w.resize(250, 150)
    #move()方法移动窗口在屏幕上的位置到x = 300,y = 300坐标。
    w.move(300, 300)
    #设置窗口的标题
    w.setWindowTitle('Simple')
    #显示在屏幕上
    w.show()

    #系统exit()方法确保应用程序干净的退出
    #的exec_()方法有下划线。因为执行是一个Python关键词。因此,exec_()代替
    sys.exit(app.exec_())

示例2:应用程序的图标

应用程序图标是一个小的图像,通常在标题栏的左上角显示。在下面的例子中我们将介绍如何做pyqt5的图标。Pyqt5使用OOP编程

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
py40 PyQt5 tutorial 

This example shows an icon
in the titlebar of the window.

author: Jan Bodnar
website: py40.com 
last edited: January 2015
"""

import sys
from PyQt5.QtCore import QFileInfo
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon # 新引入的类

# 面向对象编程有三个重要的方面:类、变量和方法。
# 这里我们创建一个新的类为Examle。Example继承自QWidget类。
class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI() #界面绘制交给InitUi方法


    def initUI(self):
        #设置窗口的位置和大小: 前两位是位置,后两位是大小
        self.setGeometry(300, 300, 300, 220)  
        #设置窗口的标题
        self.setWindowTitle('Icon')
        #设置窗口的图标,引用当前目录下的web.png图片
        # 获取根路径,动态构造图片绝对路径
        path_root = QFileInfo(__file__).absolutePath()
        print(path_root + '/qt.png')
        self.setWindowIcon(QIcon(path_root + '/qt.png'))        

        #显示窗口
        self.show()


if __name__ == '__main__':
    #创建应用程序和对象
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_()) 

示例3:显示提示语

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import (QWidget, QToolTip, 
    QPushButton, QApplication)
from PyQt5.QtGui import QFont    


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):
        # 这种静态的方法设置一个用于显示工具提示的字体。我们使用10px滑体字体。
        QToolTip.setFont(QFont('SansSerif', 10))

        # 创建一个提示,我们称之为settooltip()方法。我们可以使用丰富的文本格式
        # 用于显示关于窗体的提示
        self.setToolTip('This is a <b>QWidget</b> widget')

        # 创建一个PushButton并为他设置一个tooltip
        btn = QPushButton('Button', self)
        btn.setToolTip('This is a <b>QPushButton</b> widget')

        # 按钮大小: btn.sizeHint()显示默认尺寸
        btn.resize(btn.sizeHint())

        # 按钮位置: 移动窗口的位置
        btn.move(50, 50)       

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


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

示例4:关闭窗口

关闭一个窗口可以点击标题栏上的X。在下面的例子中,我们将展示我们如何通过编程来关闭窗口

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QWidget, QApplication,QPushButton
from PyQt5.QtCore import QCoreApplication


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):               

        qbtn = QPushButton('Quit', self)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(50, 50)       
        qbtn.clicked.connect(QCoreApplication.instance().quit)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Quit button')    
        self.show()



if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

注意:

  • initUI 方法的各个代码行是按顺序执行的
  • spyder是基于 PyQT5 开发的, 直接在 spyder中运行有问题, 可以从命令行启动。

示例5:消息框

默认情况下,如果我们单击x按钮窗口就关门了。有时我们想修改这个默认的行为。例如我们在编辑器中修改了一个文件,当关闭他的时候,我们显示一个消息框确认。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QWidget,  QApplication,QMessageBox


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):               

        self.setGeometry(300, 300, 250, 150)        
        self.setWindowTitle('Message box')    
        self.show()

    # 我们关闭窗口的时候,触发了QCloseEvent
    # 我们需要重写closeEvent()事件处理程序  

    def closeEvent(self, event):

        # 显示一个消息框,两个按钮:“是”和“不是”。
        # 第一个字符串 Message出现在titlebar
        # 第二个字符串消息对话框中显示的文本。
        # 第三个参数指定按钮的组合出现在对话框中,
        # 最后一个参数是默认按钮,这个是默认的按钮焦点。
        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()        


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

示例6:窗口显示在屏幕的中间

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
Py40 PyQt5 tutorial 

This program centers a window 
on the screen. 

author: Jan Bodnar
website: py40.com 
last edited: January 2015
"""

import sys
from PyQt5.QtWidgets import QWidget,  QApplication,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()


    # 控制窗口显示在屏幕中心的方法
    # QtGui,QDesktopWidget类提供了用户的桌面信息,包括屏幕大小。    
    def center(self):

        #获得窗口
        qr = self.frameGeometry()
        #获得屏幕中心点
        cp = QDesktopWidget().availableGeometry().center()
        #显示到屏幕中心
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())  

PyQt5布局管理

PyQt5布局有两种方式,绝对定位和布局类

1.绝对定位

程序指定每个控件的位置和大小(以像素为单位)。

绝对定位有以下限制:

  • 如果我们调整窗口,控件的大小和位置不会改变
  • 在各种平台上应用程序看起来会不一样
  • 如果改变字体,我们的应用程序的布局就会改变
  • 如果我们决定改变我们的布局,我们必须完全重做我们的布局

示例7:绝对定位,我们使用move()方法来控制控件的位置。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QWidget,  QApplication,QLabel


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

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

        lbl2 = QLabel('tutorials', self)
        lbl2.move(35, 40)

        lbl3 = QLabel('for programmers', self)
        lbl3.move(55, 70)        

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


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

2.框布局 Boxlayout

我们使用QHBoxLayout和QVBoxLayout,来分别创建横向布局和纵向布局。

示例8:

在这个例子中,我们使用HBoxLayout和QVBoxLayout并添加伸展因子,在窗口的右下角显示两个按钮。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import (QWidget,QApplication, QPushButton, 
                             QHBoxLayout, QVBoxLayout )

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        okButton = QPushButton("OK")
        cancelButton = QPushButton("Cancel")

        # 我们创建一个水平布局和添加一个伸展因子 Stretch(1) 和两个按钮。
        # 两个按钮前的伸展增加了一个可伸缩的空间。这将推动他们靠右显示。
        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, 150)
        self.setWindowTitle('Buttons')    
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

3.表格布局 QGridLayout

表格布局将空间划分为行和列。我们使用QGridLayout类创建一个网格布局。

示例9:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import (QWidget,  QApplication,QPushButton, 
                             QGridLayout)


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        # QGridLayout的实例被创建并设置为应用程序窗口的布局。
        grid = QGridLayout()
        self.setLayout(grid)

        # 按钮的标签
        names = ['Cls', 'Bck', '', 'Close',
                 '7', '8', '9', '/',
                '4', '5', '6', '*',
                 '1', '2', '3', '-',
                '0', '.', '=', '+']

        # 网格中的位置的列表
        positions = [(i,j) for i in range(5) for j in range(4)]

        # 创建不同标签的按钮并使用addWidget()方法添加到布局中
        # zip函数打包两个序列为元组列表
        for position, name in zip(positions, names):
            if name == '':
                continue
            button = QPushButton(name)
            # * 以元组形式导入参数
            grid.addWidget(button, *position)


        self.move(300, 150)
        self.setWindowTitle('Calculator')
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

示例10:评论的例子

控件可以在网格中跨越多个行或列。在下一个示例中,我们说明了这一点。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, 
    QTextEdit, QGridLayout, QApplication)


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)
        # 在添加一个小的控件到网格的时候,我们可以提供小部件的行和列跨。
        # reviewEdit控件跨度5行
        '''QGridLayout.addWidget(arg__1, row, column, rowSpan,
                        columnSpan[, alignment=Qt.Alignment()])
        这是一个重载函数。指定行、列、跨行数、跨列数和对齐方式,
        将给定控件添加至布局中。
        如果 rowSpan 和/或 columnSpan 为 -1,
        则控件将分别延伸到底部和/或右边缘'''
        grid.addWidget(reviewEdit, 3, 1, 5, 1)

        self.setLayout(grid) 

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


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

正文完
 
评论(没有评论)