PyQt是Qt库的Python版本,该教程是 zetcode PyQt4教程的中文翻译。 本文主要介绍了PyQt4的基本使用方法及基本窗口的绘制。

简单示例

第一个程序显示一个简单的窗口。 以下是原始代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 04 21:23:31 2015

@author: Arthur
an example for PyQt4 gui program.
"""

import sys
from PyQt4 import QtGui # 导入必要的模块

def main():
app = QtGui.QApplication(sys.argv) # 创建一个应用对象,sys.argv为命令行传入的参数

window = QtGui.QWidget() # QtGui.Qwidget 是所有界面对象的基础类,没有父类的部件称为窗口
window.resize(250, 150) # 调整部件大小,250px宽150px高
window.move(300, 300) # 移动部件的位置到屏幕 (x = 300, y = 300)处
window.setWindowTitle('Simple') # 设置窗口标题栏显示的标题
window.show() # 在内存中创建组件并显示在屏幕上

sys.exit(app.exec_()) # sys.exit()保证程序完全的退出

if __name__ == '__main__':
main()

显示窗口如下:

简单的窗口简单的窗口

添加应用图标(Application icon)

添加在标题栏左上角显示的应用图标,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 04 21:54:19 2015

@author: Arthur
A gui program with application icon.
use OOP(Object Oriented Programming)
"""

import sys
from PyQt4 import QtGui

class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__() # super() method 返回对象'Example'的父类

self.initUI()

def initUI(self):
self.setGeometry(300, 300, 250, 150) # 设置窗口的坐标及大小(x, y, 宽, 高)
self.setWindowTitle('Icon')
self.setWindowIcon(QtGui.QIcon('web.png')) # 设置窗口应用图标

self.show()

def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

if __name__ == '__main__':
main()

该程序以面向对象的风格书写,面向对象编程中最重要的是类(class),数据(data)和方法(method)。显示的窗口如下:

在标题栏显示程序图标在标题栏显示程序图标

显示提示信息

显示部件的气球帮助提示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 05 11:40:30 2015

@author: Arthur
show a tooltip
"""

import sys
from PyQt4 import QtGui

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

def initUI(self):
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10)) # 设置提示的字形及字体大小
self.setToolTip('This is a <b>QWidget</b> widget')

btn = QtGui.QPushButton('Button', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')
btn.resize(btn.sizeHint()) # szieHint() 返回按钮推荐的大小
btn.move(50, 50)

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

def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

if __name__ == '__main__':
main()

显示的窗口如下:

创建有气泡提示的按钮创建有气泡提示的按钮

关闭窗口

以上的例子中都是通过点击窗口右上角的X来关闭窗口,下面的例子演示了通过程序内的方法关闭窗口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 05 12:24:44 2015
@author: Arthur
A button with quit
"""


import sys
from PyQt4 import QtGui, QtCore

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

def initUI(self):
qbtn = QtGui.QPushButton('Quit', self) # 参数分别为按钮的标签及按钮的父类
qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)

qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)

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

def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

if __name__ == '__main__':
main()

该程序创建了QtGui.QPushButton类的一个实例qbtn,在以下的语句中赋予了该按钮关闭程序的功能:

1
qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
使程序退出的按钮使程序退出的按钮

PyQt4中的事件处理是由信号(signals)与槽(slots)机制实现的,如果点击按钮,将会发出clicked()的信号。槽可以是PyQt的槽或者是Python可调用的方法。通过使用QtCore.QObject.connect()方法将信号和槽链接起来。QtCore.QCoreApplication 包含了主要的事件循环,它处理和分配所有的事件。instance()方法返回它自己的实例。 应该注意的是QtCore.QCoreApplicationQtGui.QApplication一起被创建。点击信号连接到PyQt中预先定义的quit()槽。至此信号发送方与接收方之间的通信完成,发送方为点击按钮,接收方为程序对象。


消息框

当点击窗口右上角x退出时弹出确认消息框。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 05 12:38:58 2015
@author: Arthur
show message box
"""

import sys
from PyQt4 import QtGui


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

self.initUI()

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

def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure to quit?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.No) # (消息框标题, 显示消息, 选项 | 选项, 默认选项)

if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()

def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

if __name__ == '__main__':
main()
点击关闭后弹出确认消息框点击关闭后弹出确认消息框
确认关闭消息框确认关闭消息框

如果要关闭QWidgetQCloseEvent事件就会产生。要修改QWidget的默认行为,就需要重载父类中的closeEvent()方法。点击关闭按钮后,弹出如右对话框。 点击YesNo后,对replay值进行比较,如果为Yes则接收事件关闭窗口,相反则忽略事件。


居中窗口

在屏幕中央显示窗口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 05 14:42:27 2015
@author: Arthur
centering window on the screen
"""

import sys
from PyQt4 import QtGui

class Example(QtGui.QWidget):

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

self.initUI()

def initUI(self):
self.resize(250, 150)
self.center()

self.setWindowTitle('Center')
self.show()

def center(self):
qr = self.frameGeometry() # 返回代表窗口框架结构的矩形
cp = QtGui.QDesktopWidget().availableGeometry().center() # 返回屏幕(可显示区域)的中心点
qr.moveCenter(cp) # 将与窗口同大的矩形移动到屏幕中央
self.move(qr.topLeft()) # 将主窗口移动到已定位的矩形处,QWidget的移动以左上角为基准点

def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

if __name__ == '__main__':
main()

通过frameGeometry()获得代表窗口框架结构的矩形,通过availableGeometry().center()获得屏幕(可显示区域)的中心点,用moveCenter()方法将该框架矩形移动到屏幕中央,再将主窗口移动到已定位的矩形处。 由于移动窗口组件时是以组件的右上角为基准点,所以不能用self.move(cp)移动窗口到中心。 也可以在获得屏幕与窗口几何参数后直接移动窗口的左上角到计算出的目的位置:

1
2
3
screen = QtGui.QDesktopWidget().screenGeometry() # 获得屏幕形状参数
size = self.geometry() # 获得窗口形状参数
self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) # 计算出窗口左上角移动后的位置,再直接移动窗口

参考资料:

  1. First Program in PyQt4 from zetcode