python - 如何使用其唯一的 ID 将项目添加到 Qcombobox

标签 python python-3.x pyqt pyqt5 qcombobox

您有什么想法将项目添加到 Qcombobox 中吗?

当用户选择该项目时,我们可以检索所选项目的唯一 ID 吗?

假设我们有:

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

我们只想在 QCombobox 中显示 NAME 的列,但是当选择其中一项时,我们可以访问所选项目的 ID。

最佳答案

您只需使用一个模型,在一个角色中设置 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_())

关于python - 如何使用其唯一的 ID 将项目添加到 Qcombobox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53134300/

相关文章:

python - 使用 PyQt5 的语法高亮编辑器

python - wxPython:禁用笔记本选项卡?

python - Python中条件表达式的求值顺序是什么?

python-3.x - 根据 .hdf5 中的权重和 .json 中的选项在 keras 中实例化 ELMo 模型

python - 我无法让 import random 工作 - python 3

python - QTableWidget 中的输入掩码

python - 删除除第一列以外的多个同名列?

python - 检测窗口的默认媒体播放器

python - 我如何对以下词典列表进行排序?

pyqt - 如何重新启动我的 pyqt 应用程序?