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

相关推荐
用户83562907805113 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng815 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi16 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee16 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay16 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤16 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean17 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽18 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户606487671889619 小时前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听19 小时前
RAG深入学习之Chunk
前端·人工智能·python