我希望能够从子类 QComboBox 发送自定义信号。 我的测试代码如下: 目前我什么也没得到,什么也没有。 这必须是显而易见的,但我看不到解决方案。任何帮助表示赞赏。
import sys
from PyQt6.QtWidgets import QApplication, QComboBox, QDialog
from PyQt6.QtCore import QRect, pyqtSignal, QMetaObject
def happyDays(index):
print('May you receive {index} million dollars in the mail')
class MyComboBox(QComboBox): #combo box
signal = pyqtSignal(int)
def __init__(self, parent):
super(MyComboBox, self).__init__(parent)
self.setFocus()
self.setEditable(True)
self.setGeometry(QRect(5, 0, 240, 50))
self.signal.connect(happyDays)
def currentIndexChanged(self, index):
#emit a signal when combobox selection changes
print('click!')
self.signal.emit(index)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(250, 50)
Dialog.setWindowTitle("MyCombo Signal Test")
QMetaObject.connectSlotsByName(Dialog)
class Dialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
combo = MyComboBox(self)
items = ['Invertebrate','Fish','Amphibian','Reptile','Bird','Mammal', 'N/A']
print(items)
combo.addItems(items)
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = Dialog()
widget.show()
sys.exit(app.exec())
我尝试重命名“currentIndexChanged”方法,但我认为它应该重写基类方法,如图所示。我已经检查过 QComboBox 应根据文档发出“currentIndexChanged”信号。我可能把信号和槽弄混了。一个小时后,我感到茫然和困惑。
我更改了您的
MyComboBox
并将处理程序连接到其 currentIndexChanged
信号:
class MyComboBox(QComboBox): #combo box
signal = pyqtSignal(int)
def __init__(self, parent):
super(MyComboBox, self).__init__(parent)
self.setFocus()
self.setEditable(True)
self.setGeometry(QRect(5, 0, 240, 50))
self.signal.connect(happyDays)
self.currentIndexChanged.connect(lambda i: self.signal.emit(i))