使用 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 关联起来,以便在按钮被点击时更新标签的文本。我们还使用了一个垂直布局来将组件添加到窗口中。运行此代码将显示一个窗口,其中包含一个标签和一个按钮。当按钮被点击时,标签的文本将更新为显示点击事件发生的时间。

相关推荐
兵慌码乱5 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵6 小时前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio10 小时前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户03321266636711 小时前
使用 Python 从零创建 Word 文档
python
Csvn16 小时前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽17 小时前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户5569188175319 小时前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱1 天前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei1 天前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python