PyQT5訊號與槽的連線

星空28發表於2024-06-08

方法一:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys


class AutoSignalSlot(QWidget):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("訊號與槽自動連線")
        self.resize(300, 100)

        self.okButton = QPushButton("OK", self)     # 將btn繫結到視窗
        self.okButton.setObjectName('okButton')

        layout = QHBoxLayout()
        layout.addWidget(self.okButton)
        self.setLayout(layout)
        
        # 方法一
        self.okButton.clicked.connect(self.on_okButton_clicked)

    def on_okButton_clicked(self):
        print("點選了OK按鈕!")


if __name__ == '__main__':

    app = QApplication(sys.argv)
    main_win = AutoSignalSlot()
    main_win.show()
    sys.exit(app.exec_())

方法二:
訊號與槽自動連線
on_objectname_signalname
例如:on_okButton_clicked

from PyQt5.QtCore import *
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
import sys


class AutoSignalSlot(QWidget):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("訊號與槽自動連線")
        self.resize(300, 100)

        self.okButton = QPushButton("OK", self)     # 將btn繫結到視窗
        self.okButton.setObjectName('okButton')

        self.cancelButton = QPushButton("Cancel", self)     # 將btn繫結到視窗
        self.cancelButton.setObjectName('cancelButton')

        layout = QHBoxLayout()
        layout.addWidget(self.okButton)
        self.setLayout(layout)

        # 方法一
        # self.okButton.clicked.connect(self.on_okButton_clicked)
        # 方法二
        QMetaObject.connectSlotsByName(self)

    @QtCore.pyqtSlot()
    def on_okButton_clicked(self):
        print("點選了OK按鈕!")

    @QtCore.pyqtSlot()
    def on_cancelButton_clicked(self):
        print("點選了cancel按鈕!")


if __name__ == '__main__':

    app = QApplication(sys.argv)
    main_win = AutoSignalSlot()
    main_win.show()
    sys.exit(app.exec_())



相關文章