Qt for Python快速入门

一.搭建环境

  • 1.python官网下载python3.7.4 安装

https://www.python.org/ftp/python/3.7.4/python-3.7.4.exe

  • 2.命令行安装PySide2

    pip install PySide2

  • 3.安装qt 5.13

    参考帖子

二、创建demo程序

  • 1.打开qt 5.13,创建Qt for Python - Windows 程序

1563883960069.png

  • 2.在main.py里追加如下代码

追加导入

    # This Python file uses the following encoding: utf-8
    import sys
    import random
    from PySide2 import QtCore, QtWidgets, QtGui

定义MyWidget类

class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.hello = ["Hallo Welt", "Hei maailma", "Hola Mundo", "Привет мир"]

        self.button = QtWidgets.QPushButton("Click me!")
        self.text = QtWidgets.QLabel("Hello World")
        self.text.setAlignment(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)


    def magic(self):
        self.text.setText(random.choice(self.hello))

添加main函数,显示窗口

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec_())
  • 3.运行截图
    1563884627270.png

参考qt官方文档 https://doc.qt.io/qtforpython/gettingstarted.html

posted @ 2021-11-01 14:59  踏月清风  阅读(338)  评论(0编辑  收藏  举报