pyQT Combobox print output upon changed

后端 未结 1 1461
难免孤独
难免孤独 2021-01-24 02:52

I want to create an event (print in this case) based on which combox and which row in the combox. I had a look on this old post and made some extension. Does it make some sense?

相关标签:
1条回答
  • 2021-01-24 03:10

    It is not necessary to use lambda functions to send additional information if QComboBox is used, QComboBox can store information for each index, addItem() has an additional parameter where information can be saved and we can access it through the itemData() method, we can add another information with the setItemData() method.

    To know that QComboBox emitted the signal we can use sender(), this method returns the object that emits the signal.

    All of the above is implemented in the following example:

    from PyQt4 import QtCore, QtGui
    import sys
    
    class myWindow(QtGui.QWidget):
        def __init__(self, parent=None):
            super(myWindow, self).__init__(parent)
    
            lay = QtGui.QHBoxLayout(self)
            test = [['first', 1], ['second', 2]]
    
            for j in range(5):
                comboBox = QtGui.QComboBox(self)
                lay.addWidget(comboBox)
                for i, values in enumerate(test):
                    text, data = values
                    comboBox.addItem(text, (j, data))
                comboBox.currentIndexChanged.connect(self.onCurrentIndexChanged)
    
        @QtCore.pyqtSlot(int)
        def onCurrentIndexChanged(self, ix):
            combo = self.sender()
            row, column = combo.itemData(ix)
            print(row, column)
    
    
    if __name__ == "__main__":
        app = QtGui.QApplication(sys.argv)
        app.setApplicationName('myApp')
        dialog = myWindow()
        dialog.show()
        sys.exit(app.exec_())
    
    0 讨论(0)
提交回复
热议问题