【问题标题】:how to add items to Qcombobox with its unique Id如何使用其唯一 ID 将项目添加到 Qcombobox
【发布时间】:2019-04-07 15:02:18
【问题描述】:

你有什么想法可以将项目添加到 Qcombobox 中吗?

随着用户选择商品的时间,我们可以检索到所选择商品的唯一ID吗?

假设我们有:

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

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

【问题讨论】:

    标签: python python-3.x pyqt pyqt5 qcombobox


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 2012-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 2022-01-09
      • 2012-11-09
      相关资源
      最近更新 更多