内容表

上一话题

Qt for Python 文档编制

下一话题

Qt for Python 入门

Qt for Python 快速入门

要求

在可以安装 Qt for Python 之前,首先必须安装下列软件:

安装

现在准备安装 Qt for Python 包使用 pip 。从终端,运行以下命令:

pip install PySide2 # For the latest version on PyPi
									

或:

pip install --index-url=http://download.qt.io/snapshots/ci/pyside/5.14/latest pyside2 --trusted-host download.qt.io
									

测试您的安装

Now that you have Qt for Python installed, you can test your setup by running the following Python constructs to print version information:

import PySide2.QtCore
# Prints PySide2 version
# e.g. 5.11.1a1
print(PySide2.__version__)
# Gets a tuple with each version component
# e.g. (5, 11, 1, 'a', 1)
print(PySide2.__version_info__)
# Prints the Qt version used to compile PySide2
# e.g. "5.11.2"
print(PySide2.QtCore.__version__)
# Gets a tuple with each version components of Qt used to compile PySide2
# e.g. (5, 11, 2)
print(PySide2.QtCore.__version_info__)
									

创建简单应用程序

Your Qt for Python setup is ready. You can explore it further by developing a simple application that prints “Hello World” in several languages. The following instructions will guide you through the development process:

  1. 创建新文件名为 hello_world.py ,并为它添加以下 import:

    import sys
    import random
    from PySide2 import QtCore, QtWidgets, QtGui
    											

The PySide2 Python module provides access to the Qt APIs as its submodule. In this case, you are importing the QtCore , QtWidgets ,和 QtGui 子模块。

  1. 定义类名 MyWidget ,扩展 QWidget 并包括 QPushButton 及 QLabel:

    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))
    											

MyWidget 类拥有 magic member function that randomly chooses an item from the hello list. When you click the button, the magic 函数被调用。

  1. 现在,添加 main 函数实例化 MyWidget and show it.:

    if __name__ == "__main__":
        app = QtWidgets.QApplication([])
        widget = MyWidget()
        widget.resize(800, 600)
        widget.show()
        sys.exit(app.exec_())
    											

运行范例。试着点击底部按钮以查看获得的问候。

Hello World application