温馨提示×

python qpushbutton的自定义信号如何使用

小樊
83
2024-09-06 15:27:35
栏目: 编程语言

在 PyQt5 中,要创建自定义信号并在 QPushButton 上使用它们,需要先导入相关库,然后创建一个新的信号并将其与按钮的点击事件(clicked)连接

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
from PyQt5.QtCore import pyqtSignal

class CustomPushButton(QPushButton):
    custom_signal = pyqtSignal()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.clicked.connect(self.emit_custom_signal)

    def emit_custom_signal(self):
        self.custom_signal.emit()

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        vbox = QVBoxLayout()

        button = CustomPushButton("Click me")
        button.custom_signal.connect(self.on_custom_signal)

        vbox.addWidget(button)
        self.setLayout(vbox)

    def on_custom_signal(self):
        print("Custom signal emitted!")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

在这个示例中,我们首先从 QPushButton 类创建了一个名为 CustomPushButton 的子类。我们定义了一个名为 custom_signal 的自定义信号,并在按钮被点击时触发它。

然后,在 MainWindow 类中,我们创建了一个 CustomPushButton 实例,并将其自定义信号连接到 on_custom_signal 方法。当按钮被点击时,这个方法会被调用,输出 “Custom signal emitted!”。

0