mehdi parastar
mehdi parastar

Reputation: 827

how to add items to Qcombobox with its unique Id

Do you have any idea to add items into Qcombobox?

as the time the user selects the item,we can retrieve the unique Id's of selected item?

suppose that we have:

=============
| ID | NAME |
=============
| 1  |   A  |
=============
| 2  |   B  |
=============
| 3  |   C  |
=============
| 4  |   D  |
=============

AND we want to show only NAME's column in QCombobox, but when one of the items had selected,we can access to ID of selected item.

Upvotes: 1

Views: 3471

Answers (1)

eyllanesc
eyllanesc

Reputation: 243907

You just have to use a model, set the ID in one of the roles and the NAME in another, in the next part I show an example:

from PyQt5 import QtCore, QtGui, QtWidgets


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)


    data =  [(1, "A"), (2, "B"), (3, "C"), (4, "D")]
    model = QtGui.QStandardItemModel()
    for i, text in data:
        it = QtGui.QStandardItem(text)
        it.setData(i)
        model.appendRow(it)

    @QtCore.pyqtSlot(int)
    def on_currentIndexChanged(row):
        it = model.item(row)
        _id = it.data()
        name = it.text()
        print("selected name: ",name, ", id:", _id)

    w = QtWidgets.QComboBox()
    w.currentIndexChanged[int].connect(on_currentIndexChanged)
    w.setModel(model)
    w.show()
    sys.exit(app.exec_())

Upvotes: 2

Related Questions