简体   繁体   English

如何使用其唯一的ID向Qcombobox添加项目

[英]how to add items to Qcombobox with its unique Id

Do you have any idea to add items into Qcombobox? 您是否有将项目添加到Qcombobox的想法?

as the time the user selects the item,we can retrieve the unique Id's of selected item? 当用户选择项目时,我们可以检索所选项目的唯一ID?

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. 并且我们只想在QCombobox中显示“ NAME”列,但是当选择了一项时,我们可以访问所选项目的ID。

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: 您只需要使用一个模型,在一个角色中设置ID,在另一个角色中设置NAME,在下一部分中,我将显示一个示例:

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_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM