PyQt - QComboBox connection confirmed but function

2020-03-06 07:26发布

问题:

I am having a bit of trouble with the signal/slot issues using PyQt. My code is below, but it probably deserves a bit of explanation. The first two QObject.connect() return True, so I know the connection is established. However, when changing the selection in the comboBox, the function getParameters is not called as expected. The 5 connects below that were for debugging and testing the other signals associated with ComboBox. Those do not print the the log as expected either.

From what I've read else where there are newer ways to specify a connection, could this be the issue? And if so, can someone give me an example of that format? Thanks!

#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:

I solved it. As I guessed, it did have to do with the "new style" connection syntax. I'm not entirely sure why the old style was connecting, but not calling the connected function, but it is now working with the following code:

    self.dlg.ui.comboBox.currentIndexChanged['QString'].connect(self.getParameters)
    self.dlg.ui.spinBox_bands.valueChanged.connect(self.getParameters)

For those that don't know (I didn't and couldn't find good docmentation - link?), the ['QString'] argument allows you to select the type of result for overloaded signals. This was important for me as I'm using the type to distinguish between the senders. However, I suppose I should be more explicit and use

sender = self.sender()

in my getParameters function, but this is working.