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

相关推荐
明月_清风37 分钟前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽10 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805115 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon16 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly16 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程16 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly18 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法