PyQt 高级部分学习 - 第一篇

自定义组件和信号槽机制

在这一篇中,我们将探讨如何在 PyQt 中创建自定义组件和使用高级的信号槽机制。

自定义组件

自定义组件允许你创建具有特定功能和外观的新组件。下面是一个自定义按钮组件的示例:

python 复制代码
from PyQt5.QtWidgets import QPushButton, QApplication, QWidget, QVBoxLayout

class MyCustomButton(QPushButton):
    def __init__(self, text):
        super().__init__(text)
        self.setFixedSize(100, 50)

    def mousePressEvent(self, event):
        print("Custom button clicked!")

app = QApplication([])
window = QWidget()
layout = QVBoxLayout()

button = MyCustomButton("Click Me")
layout.addWidget(button)

window.setLayout(layout)
window.show()
app.exec_()

高级信号槽机制

PyQt 的信号槽机制不仅限于简单的点击事件,还可以传递参数和使用自定义信号。

python 复制代码
from PyQt5.QtCore import pyqtSignal, QObject

class MySignal(QObject):
    my_custom_signal = pyqtSignal(str)

    def run(self):
        self.my_custom_signal.emit("Hello, World!")

def my_slot(message):
    print("Received:", message)

signal_instance = MySignal()
signal_instance.my_custom_signal.connect(my_slot)
signal_instance.run()

Model-View-Controller (MVC) 模式

在 PyQt 中,你可以使用 MVC 模式来组织代码和分离关注点。

python 复制代码
# Model
class MyModel:
    def get_data(self):
        return ["Item 1", "Item 2", "Item 3"]

# View
class MyView(QWidget):
    def __init__(self, model):
        super().__init__()
        self.model = model
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()
        data = self.model.get_data()
        for item in data:
            layout.addWidget(QPushButton(item))
        self.setLayout(layout)

# Controller
class MyController:
    def __init__(self):
        self.model = MyModel()
        self.view = MyView(self.model)
        self.view.show()

app = QApplication([])
controller = MyController()
app.exec_()

总结

在这篇文章中,我们探讨了如何在 PyQt 中创建自定义组件,使用高级的信号槽机制,以及如何使用 MVC 模式来组织代码。这些高级特性将有助于你创建更加复杂和可维护的 PyQt 应用程序。

相关推荐
追逐时光者12 分钟前
DotNetGuide突破了10K + Star,一份全面且免费的C#/.NET/.NET Core学习、工作、面试指南知识库!
后端·.net
yuweiade34 分钟前
springboot和springframework版本依赖关系
java·spring boot·后端
ywf121535 分钟前
springboot设置多环境配置文件
java·spring boot·后端
小马爱打代码1 小时前
SpringBoot + 消息生产链路追踪 + 耗时分析:从创建到发送,全链路性能可视化
java·spring boot·后端
小码哥_常1 小时前
MyBatis批量插入:从5分钟到3秒的逆袭之路
后端
烛之武2 小时前
SpringBoot基础
java·spring boot·后端
橙序员小站3 小时前
Harness Engineering:从 OpenClaw 看 AI 助理的基础设施建设
后端·aigc·openai
小陈工3 小时前
2026年3月28日技术资讯洞察:5G-A边缘计算落地、低延迟AI推理革命与工业智造新范式
开发语言·人工智能·后端·python·5g·安全·边缘计算
azhou的代码园4 小时前
基于SpringBoot+微信小程序的图片识别科普系统
spring boot·后端·微信小程序
Tony Bai4 小时前
Rust 看了流泪,AI 看了沉默:扒开 Go 泛型最让你抓狂的“残疾”类型推断
开发语言·人工智能·后端·golang·rust