Hello QT

简评:PySide2 是 QT 官方出品,值得期待
PySide2 第一个技术预览版快要发布了,在此给出一个简单的例子,来展示它将如何打开 Python世界的大门。

下面我们将使用 QWidgets 构建一个简单的应用来展示 PySide2 的简洁性,每个脚本都具有或多或少相同的结构:

创建一个QApplication
然后包含所有想要使用的 QWidgets 和结构(例如 QLabel)
显示应用程序并启动 QApplication
放在一起,将会是这样的东西:

hello_world.py

from PySide2.QtWidgets import QApplication, QLabel

app = QApplication([])
label = QLabel("Hello Qt for Python!")
label.show()
app.exec_()
使用 python hello_world.py 命令就可以执行这段脚本。但这不是全部,真正的问题是:如何访问 Qt 类的方法?为了简化这个过程,我们保留了 Qt API,例如,如果我们想要指定一个 QLabel 的大小,在 C++ 中我们会这样写:

QLabel *label = new QLabel();
label->setText("Hello World!");
label->resize(800, 600);
使用 PySide2 的写法是:

label = QLabel()
label.setText("Hello World!")
label.resize(800, 600)
现在我们知道了 C++ 的等价写法,就可以编写更复杂的应用程序。

import sys
import random
from PySide2.QtCore import Qt
from PySide2.QtWidgets import (QApplication, QWidget,
QPushButton, QLabel, QVBoxLayout)

class MyWidget(QWidget):
def init(self):
QWidget.init(self)

self.hello = ["Hallo welt!", "Ciao mondo!",
"Hei maailma!", "Hola mundo!", "Hei verden!"]

self.button = QPushButton("Click me!")
self.text = QLabel("Hello World")
self.text.setAlignment(Qt.AlignCenter)

self.layout = 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))

if name == "main":
app = QApplication(sys.argv)
widget = MyWidget()
widget.resize(800, 600)
widget.show()
sys.exit(app.exec_())
如果你还不熟悉 Qt 开发,那么扩展某个类并将其改写以适应我们的需求是一种常见做法,在上面的例子中,我们使用 QWidget 作为基类,并包含了一个 QLabel 和 QPushButton。

该应用非常简单:

首先,我们编写包含许多种语言的 Hello World 的写法的列表。
然后,我们用一定的对齐,字体和大小初始化一个 QPushButton 和一个 QLabel。
之后,我们创建一个 QVBoxLayout 来包含我们的对象,并将其分配给我们的类。
最后,我们将 QPushButton 的 clicked() 信号连接到我们称为 magic 的方法。
因此,每次点击按钮,我们都会以随机语言获得 Hello World!

这个简单的脚本的结构将成为大多数使用 Pyside2 的应用程序的基础。

原文:Hello Qt for Python

猜你喜欢

转载自www.cnblogs.com/jpush88/p/9171693.html
今日推荐