Search code examples
pythonpyqtpyqt5qcomboboxqt-signals

Using new style signal and slots for combobox?


I have two lines using the old SIGNAL and SLOT style..

combobox.emit(SIGNAL("activated(int)"), combobox.currentIndex())
combobox.emit(SIGNAL("activated(const QString &)"), combobox.currentText())

I was wondering what the new style would look like. I'm new to python and I don't have much experience with signals and slots. Is there a really good resource floating around that covers this? The documentation didn't really help me understand what was going on.


Solution

  • The solution is to indicate the type of argument of the signal that is being emitted:

    combo.activated[type].connect(someSlot)
    

    Example:

    class Widget(QWidget):
        def __init__(self, parent=None):
            QWidget.__init__(self, parent)
            self.setLayout(QVBoxLayout())
            combo = QComboBox(self)
            self.layout().addWidget(combo)
            combo.addItems(["item1", "item2", "item3"])
            combo.activated[int].connect(self.onActivatedIndex)
            combo.activated[str].connect(self.onActivatedText)
    
        @pyqtSlot(int)
        def onActivatedIndex(self, index):
            print(index)
    
        @pyqtSlot(str)
        def onActivatedText(self, text):
            print(text)
    
    
    if __name__ == '__main__':
        import sys
        app = QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())