携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情
PySide2是一个Python模块,它提供了对Qt5.12+完整框架的访问,简单点说就是在Python下使用的Qt。使用PySide2既能开发出完美的界面,又能享受Python的便捷开发。与PySide和PyQt相比,PySide2是开源的,使用不受限制;与Qt的C++相比,使用PySide2能大大减少代码量。PySide2的这些优点,很适合团队规模不大,项目需要快速推进,需开发精美界面的场合。
1.pyside2 安装
安装很简单,直接pip安装即可。
# 最新版
pip install PySide2
# 指定版本
pip install PySide2\==5.15.0
# 指定安装地址
pip install \--index\-url\=http://download.qt.io/snapshots/ci/pyside/5.15/latest pyside2 \--trusted\-host download.qt.io
2.测试
安装完毕,可以查看版本
import PySide2.QtCore
# Prints PySide2 version
print(PySide2.__version__)
# Prints the Qt version used to compile PySide2
print(PySide2.QtCore.__version__)
3.创建HelloWorld
最简单的就是创建一个Widget,然后创建一个QApplication,运行即可。
import sys
import random
from PySide2 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.hello = ["Hallo World", "What's this?", "Who are you?", "Ken"]
self.button = QtWidgets.QPushButton("Click me!")
self.text = QtWidgets.QLabel("Hello World",
alignment=QtCore.Qt.AlignCenter)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.text)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
self.button.clicked.connect(self.magic)
@QtCore.Slot()
def magic(self):
self.text.setText(random.choice(self.hello))
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.resize(800, 600)
widget.show()
sys.exit(app.exec_())