hello world by Qt
使用 Qt Quick 创建第一个 Qt 应用程序:
import sys
import random
from PySide6 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__() # 调用父类的初始化方法
self.hello = ["Hallo Welt", "Hei maailma", "Hola Mundo", "Привет мир"] # 定义一个包含多种问候语的列表
self.button = QtWidgets.QPushButton("Click me!") # 创建一个按钮,文本为"Click me!"
self.text = QtWidgets.QLabel("Hello World", # 创建一个标签,初始文本为"Hello World"
alignment=QtCore.Qt.AlignCenter) # 文本居中对齐
self.layout = QtWidgets.QVBoxLayout(self) # 创建一个垂直布局
self.layout.addWidget(self.text) # 将标签添加到布局中
self.layout.addWidget(self.button) # 将按钮添加到布局中
self.button.clicked.connect(self.magic) # 当按钮被点击时,连接到'magic'方法
@QtCore.Slot() # 定义一个槽函数
def magic(self):
self.text.setText(random.choice(self.hello)) # 从'hello'列表中随机选择一个元素设置为标签的文本
if __name__ == "__main__":
app = QtWidgets.QApplication([]) # 创建应用程序对象
widget = MyWidget() # 创建'MyWidget'类的实例
widget.resize(800, 600) # 设置窗口大小
widget.show() # 显示窗口
sys.exit(app.exec()) # 启动应用程序的事件循环,并在退出时返回状态码