1. 程式人生 > >PyQt訊號和槽

PyQt訊號和槽

MyParent.ui裡有一個QPushbutton

將ui檔案轉為py檔案->MyParent.py

MySon.py:

class MySon(QDialog, MyParent.Ui_Dialog):
helpSignal = pyqtSignal(str)
    def __init__(self):
super().__init__(None)
        self.setupUi(self)
        self.num = 0
self.helpSignal.connect(self.showHelpMessage)

        self.btnYes = QtWidgets.QPushButton
(self) self.btnYes.clicked.connect(self.on_btnYes_clicked) self.btnYes.setGeometry(QtCore.QRect(0, 0, 60, 20)) self.btnYes.setText('按鈕') self.pushButton.clicked.connect(self.on_MyPushButton_clicked) def keyPressEvent(self, event): if event.key() == Qt.Key_F1: self.helpSignal.emit
("help message") def showHelpMessage(self, message): self.num += 1 print(self.num) print(message) def on_btnYes_clicked(self): self.num += 1 print(self.num) def on_MyPushButton_clicked(self): print('on_pushButton_clicked')

訊號和槽之間引數傳遞的幾種情況:

from PyQt5.QtWidgets import QPushButton, QComboBox
from 
functools import partial class MySon(QDialog, MyParent.Ui_Dialog): def __init__(self): super().__init__(None) self.setupUi(self) self.__first = QPushButton(self) self.__second = QPushButton(self) self.__cbx_first = QComboBox(self) self.__cbx_second = QComboBox(self) self.__cbx_first.addItem('a') self.__cbx_first.addItem('b') self.__cbx_first.addItem('c') self.__cbx_second.addItem('d') self.__cbx_second.addItem('e') self.__cbx_second.addItem('f') self.__first.setGeometry(200, 200, 80, 20) self.__second.setGeometry(280, 200, 80, 20) self.__cbx_first.setGeometry(360, 200, 80, 20) self.__cbx_second.setGeometry(440, 200, 80, 20) self.__first.clicked.connect(partial(self.function, 4)) self.__second.clicked.connect(lambda: self.function(2)) self.__cbx_first.currentIndexChanged.connect(lambda: self.function(3)) self.__cbx_second.currentIndexChanged[int].connect(self.cbxfun) self.__cbx_second.currentIndexChanged[str].connect(self.cbxfun2) def function(self, num): print(num) def cbxfun(self, index): print(index) def cbxfun2(self, s): print(s)

第一個PushButton按下後會打出數字4

第二個PushButton按下後會打出數字2

第一個ComboBox選擇不同選項時會打出3

第二個ComboBox選擇不同選項時分別會打出

"0

d",

"1

e",

"2

f"