Contents
  1. 1. 版本说明
  2. 2. PySide6
    1. 2.1. PySide6工具
    2. 2.2. 概念
    3. 2.3. Hello World
    4. 2.4. 开发流程实例
    5. 2.5. 根据ui文件生成界面
    6. 2.6. 启动应用
  3. 3. PyQT5
    1. 3.1. install
    2. 3.2. create window
    3. 3.3. button

版本说明

PyQt6和PySide6都是用于调用Qt6API的Python库,使用它们可以轻松在Python语言中创建基于Qt的GUI程序;
PyQt6和PySide6最大的不同表现在发行许可上;

PyQt6是由RiverbankComputing公司开发,出现的比较早;它采用GPLv3许可证和商业许可证发布;这表示你如果使用PyQt6,则必须将你的代码进行开源;如果要闭源,则需要购买商业许可;

PySide6是Qt官方的库亲儿子,出现的时间要比PyQt晚的多,这也是很多人知道PyQt不知道PySide的原因;但随着版本的迭代,PySide6越来越强大,作者更看好PySide;

PySide6采用LGPL许可发布,这意味着只要你以调用动态链接库的形式使用Qt,你可以以任何形式(商业、非商业、开源、非开源)发布你的程序;

PySide6

pip install pyside6

PySide6工具

工具:

  • designer.exe,Qt Designer,可轻松画出UI;
  • uic.exe,用于将.ui文件转换成.py文件;
  • rcc.exe,把编写的.qrc资源文件换成.py文件;

Pycharm工具配置:
File - Settings - Tools - External Tools,点击 + Create Tool配置。
(选中要处理的文件后)依次点击 Tools - External Tools 即可启动对应工具。

1
2
3
Name: QtDisigner
Program : C:\Users\Manhua\AppData\Local\Programs\Python\Python310\Lib\site-packages\PySide6\designer.exe
Working directory: $FileDir$
1
2
3
4
Name: PyUIC
Program : C:\Users\Manhua\AppData\Local\Programs\Python\Python310\Scripts\pyside6-uic.exe
Arguments: $FileName$ -o $FileNameWithoutExtension$.py
Working directory: $FileDir$
1
2
3
4
Name: PyRCC
Program : C:\Users\Manhua\AppData\Local\Programs\Python\Python310\Scripts\pyside6-rcc.exe
Arguments: $FileName$ -o $FileNameWithoutExtension$_rc.py
Working directory: $FileDir$

概念

QApplication 对于任何使用Qt的GUI应用程序,都只有一个QApplication对象,提供基于QWidget 的应用程序所需的一些功能
QWidget类是所有用户界面对象的基类
QMainWindow 类提供一个有菜单条、锚接窗口(例如工具条)和一个状态条的主应用程序窗口。
QDialog类是对话框窗口的基类
信号 signal → 事件
槽 slot → 回调函数

Hello World

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import sys
from PySide6 import QtCore, QtWidgets, QtGui

class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.button = QtWidgets.QPushButton("点这里")
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addWidget(self.button)
self.button.clicked.connect(self.showMessage)

@QtCore.Slot()
def showMessage(self):
msgBox = QtWidgets.QMessageBox()
msgBox.setText("Hello world")
msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
ret = msgBox.exec()

if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.resize(300, 200)
widget.show()
sys.exit(app.exec())

开发流程实例

  • designer绘制界面 设置信号/槽
  • 由ui生成界面显示py文件 修改回调函数(每次更新ui后都要处理)
  • 新建业务逻辑py文件,导入界面文件

实战参考

Weather.py

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# -*- coding: utf-8 -*-

################################################################################
## Form generated from reading UI file 'Weather.ui'
##
## Created by: Qt User Interface Compiler version 6.3.0
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################

from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
QMetaObject, QObject, QPoint, QRect,
QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
QFont, QFontDatabase, QGradient, QIcon,
QImage, QKeySequence, QLinearGradient, QPainter,
QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QComboBox, QDialog, QGroupBox,
QLabel, QPushButton, QSizePolicy, QTextEdit,
QWidget)

class Ui_Dialog(object):
def setupUi(self, Dialog):
if not Dialog.objectName():
Dialog.setObjectName(u"Dialog")
Dialog.resize(400, 300)
self.queryButton = QPushButton(Dialog)
self.queryButton.setObjectName(u"queryButton")
self.queryButton.setGeometry(QRect(100, 240, 75, 24))
self.clearButton = QPushButton(Dialog)
self.clearButton.setObjectName(u"clearButton")
self.clearButton.setGeometry(QRect(210, 240, 75, 24))
self.groupBox = QGroupBox(Dialog)
self.groupBox.setObjectName(u"groupBox")
self.groupBox.setGeometry(QRect(10, 20, 371, 201))
self.label = QLabel(self.groupBox)
self.label.setObjectName(u"label")
self.label.setGeometry(QRect(30, 30, 51, 16))
self.comboBox = QComboBox(self.groupBox)
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.setObjectName(u"comboBox")
self.comboBox.setGeometry(QRect(100, 30, 68, 22))
self.textEdit = QTextEdit(self.groupBox)
self.textEdit.setObjectName(u"textEdit")
self.textEdit.setGeometry(QRect(30, 60, 311, 131))

self.retranslateUi(Dialog)
self.queryButton.clicked.connect(Dialog.queryWeather)
self.clearButton.clicked.connect(Dialog.clearText)

QMetaObject.connectSlotsByName(Dialog)
# setupUi

def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QCoreApplication.translate("Dialog", u"Dialog", None))
self.queryButton.setText(QCoreApplication.translate("Dialog", u"Query", None))
self.clearButton.setText(QCoreApplication.translate("Dialog", u"Clear", None))
self.groupBox.setTitle(QCoreApplication.translate("Dialog", u"city weather", None))
self.label.setText(QCoreApplication.translate("Dialog", u"City", None))
self.comboBox.setItemText(0, QCoreApplication.translate("Dialog", u"\u5317\u4eac", None))
self.comboBox.setItemText(1, QCoreApplication.translate("Dialog", u"\u4e0a\u6d77", None))
self.comboBox.setItemText(2, QCoreApplication.translate("Dialog", u"\u5929\u6d25", None))

# retranslateUi

MainWeather.py

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# coding:utf-8

import sys
import Weather
import requests
from PySide6.QtWidgets import QApplication, QDialog


class MainDialog(QDialog):
def __init__(self, parent=None):
super(MainDialog, self).__init__(parent)
self.ui = Weather.Ui_Dialog()
self.ui.setupUi(self)

def queryWeather(self):
print(self.ui.comboBox.currentIndex())
cityName = self.ui.comboBox.currentText()
cityCode = self.getCode(cityName)

r = requests.get("http://t.weather.sojson.com/api/weather/city/{}".format(cityCode))

print(r.json())

if r.json().get('status') == 200:
weatherMsg = '城市:{}\n日期:{}\n天气:{}\nPM 2.5:{} {}\n温度:{}\n湿度:{}\n风力:{}\n\n{}'.format(
r.json()['cityInfo']['city'],
r.json()['data']['forecast'][0]['ymd'],
r.json()['data']['forecast'][0]['type'],
int(r.json()['data']['pm25']),
r.json()['data']['quality'],
r.json()['data']['wendu'],
r.json()['data']['shidu'],
r.json()['data']['forecast'][0]['fl'],
r.json()['data']['forecast'][0]['notice'],
)
else:
weatherMsg = '天气查询失败,请稍后再试!'

self.ui.textEdit.setText(weatherMsg)

def getCode(self, cityName):
cityDict = {"北京": "101010100",
"上海": "101020100",
"天津": "101030100"}

return cityDict.get(cityName, '101010100')

def clearText(self):
self.ui.textEdit.clear()


if __name__ == '__main__':
myapp = QApplication(sys.argv)
myDlg = MainDialog()
myDlg.show()
sys.exit(myapp.exec())

根据ui文件生成界面

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
import sys

from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader

class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.load_ui()

def load_ui(self):
loader = QUiLoader()

ui_file = QFile("form.ui")
ui_file.open(QFile.ReadOnly)
self.ui = loader.load(ui_file, self)
ui_file.close()


if __name__ == "__main__":
app = QApplication([])
windows = MainWindow()
windows.ui.show()
sys.exit(app.exec())

启动应用

1
2
3
4
import os
os.system("calc")
os.system("notepad")
os.system("start msedge www.baidu.com")
1
2
3
4
5
6
7
8
from PySide6.QtCore import QProcess
process = QProcess()
process.start("notepad.exe")
process.close()

from PySide6.QtCore import QUrl
from PySide6.QtGui import QDesktopServices
QDesktopServices.openUrl(QUrl("https://blog.csdn.net"))

PyQT5

install

pip install pyqt5

https://pythonpyqt.com/pyqt-hello-world/

create window

1
2
3
4
5
6
7
8
9
10
11
12
import sys
from PyQt5 import QtWidgets

app = QtWidgets.QApplication(sys.argv)
windows = QtWidgets.QWidget() # constructor without a parent is called a window

windows.show()

windows.resize(500,500)
windows.move(300,300)
windows.setWindowTitle('Title')
sys.exit(app.exec_())

button

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout

if __name__ == '__main__':
app = QApplication(sys.argv)
w = QWidget()
layout = QHBoxLayout()
btn = QPushButton("Hello World!")
layout.addWidget(btn)
w.setLayout(layout)
w.resize(250, 150)
w.move(300, 300)
w.setWindowTitle('Simple')
w.show()
sys.exit(app.exec_())