使用 PyQt 实现简单数据绑定和组件化

下面是一个使用 PyQt 实现简单数据绑定和组件化的示例代码:

复制代码
python复制代码

|---|-------------------------------------------------------------------------------|
| | import sys |
| | from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QPushButton |
| | |
| | class Example(QWidget): |
| | def __init__(self): |
| | super().__init__() |
| | self.initUI() |
| | |
| | def initUI(self): |
| | self.setWindowTitle('PyQt Example') |
| | self.setGeometry(300, 300, 300, 200) |
| | |
| | # 创建标签和按钮组件 |
| | label = QLabel('Hello World!', self) |
| | button = QPushButton('Click me!', self) |
| | |
| | # 将按钮的点击事件与自定义函数关联 |
| | button.clicked.connect(self.on_click) |
| | |
| | # 创建垂直布局并将组件添加到布局中 |
| | layout = QVBoxLayout() |
| | layout.addWidget(label) |
| | layout.addWidget(button) |
| | |
| | # 将布局设置为窗口的布局 |
| | self.setLayout(layout) |
| | |
| | def on_click(self): |
| | # 在标签中显示点击事件发生的时间 |
| | label = self.findChild(QLabel) |
| | label.setText('Button clicked at: ' + str(self.button.text())) |
| | |
| | if __name__ == '__main__': |
| | app = QApplication(sys.argv) |
| | ex = Example() |
| | ex.show() |
| | sys.exit(app.exec_()) |

在这个示例中,我们创建了一个名为 Example 的窗口类,其中包含一个标签和一个按钮组件。我们将按钮的点击事件与自定义函数 on_click 关联起来,以便在按钮被点击时更新标签的文本。我们还使用了一个垂直布局来将组件添加到窗口中。运行此代码将显示一个窗口,其中包含一个标签和一个按钮。当按钮被点击时,标签的文本将更新为显示点击事件发生的时间。

相关推荐
ZhengEnCi1 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi3 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽3 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187914 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L21 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅21 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅21 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L21 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅21 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L1 天前
python的类&继承
python