PyQt - QComboBox已连接但函数未被调用
我在使用PyQt的时候遇到了一些信号和槽的问题。我的代码在下面,但可能需要解释一下。前两个QObject.connect()返回了True,这说明连接是成功的。不过,当我在下拉框(comboBox)中更改选择时,getParameters这个函数并没有像预期那样被调用。下面的五个连接是为了调试和测试与下拉框相关的其他信号,但它们也没有按预期打印日志。
根据我在其他地方看到的,有更新的方式来指定连接,这可能是问题所在?如果是这样的话,有人能给我一个这种格式的例子吗?谢谢!
#interactive GUI connections:
resultCombo = QObject.connect(self.dlg.ui.comboBox, SIGNAL("currentIndexChanged(const QString & text)"), self.getParameters)
resultSpin = QObject.connect(self.dlg.ui.spinBox_bands, SIGNAL("valueChanged(int i)"), self.getParameters)
QMessageBox.information( self.iface.mainWindow(),"Info", "connections: ComboBox = %s SpinBox = %s"%(str(resultCombo), str(resultSpin)) )
QObject.connect(self.dlg.ui.comboBox, SIGNAL("currentIndexChanged(const QString & text)"), self.log1)
QObject.connect(self.dlg.ui.comboBox, SIGNAL("currentIndexChanged(int index)"), self.log2)
QObject.connect(self.dlg.ui.comboBox, SIGNAL("currentTextChanged(const QString & text)"), self.log3)
QObject.connect(self.dlg.ui.comboBox, SIGNAL("highlighted(const QString & text)"), self.log4)
QObject.connect(self.dlg.ui.comboBox, SIGNAL("activated(const QString & text)"), self.log5)
def log1(self, input):
QgsMessageLog.logMessage("currentIndexChanged string. input = " + str(input), "Debug", 0)
def log2(self, input):
QgsMessageLog.logMessage("currentIndexChanged int. input = " + str(input), "Debug", 0)
def log3(self, input):
QgsMessageLog.logMessage("currentTextChanged string. input = " + str(input), "Debug", 0)
def log4(self, input):
QgsMessageLog.logMessage("highlighted string. input = " + str(input), "Debug", 0)
def log5(self, input):
QgsMessageLog.logMessage("cactivated string. input = " + str(input), "Debug", 0)
1 个回答
4
我解决了这个问题。正如我猜测的那样,这确实和“新风格”的连接语法有关。我不太明白为什么旧风格可以连接,但却没有调用连接的函数,不过现在用以下代码可以正常工作了:
self.dlg.ui.comboBox.currentIndexChanged['QString'].connect(self.getParameters)
self.dlg.ui.spinBox_bands.valueChanged.connect(self.getParameters)
对于那些不知道的人(我之前也不知道,找不到好的文档 - 链接?),这个 ['QString'] 参数可以让你选择重载信号的结果类型。这对我来说很重要,因为我用这个类型来区分发送者。不过,我想我应该更明确一点,在我的 getParameters 函数中使用
sender = self.sender()
,但现在这样也能正常工作。