如何从Qcombobox获取模型索引

问题描述 投票:0回答:1

我使用 setModel 方法填充 Qcombobox:


    def fill_cbo(self, list, cboBox):
        d = tuple(list)
        print(d)
      
        model = QtGui.QStandardItemModel()
        for id_, value in d:
            it = QtGui.QStandardItem(value)
            it.setData(id_, IdRole)
            model.appendRow(it)

        if cboBox == 'casesCbo':
            self.casesCbo.setModel(model)

稍后在程序中,当用户选择组合框中的项目时,我想访问模型索引。问题是我无法再直接访问模型,caseCbo.CurrentIndex() 只是给我基于整数的索引。如何访问模型索引或更具体地说是元组中的第一项?

我尝试了 caseCbo.item(Data()) 但它不起作用

python pyqt5 qcombobox
1个回答
0
投票

currentIndex()
函数返回组合框的索引,该组合框是一个单维小部件,因此仅返回“行”号。

如果您想要 QModelIndex,您需要访问组合model

    def getModelIndex(self, index, combo):
        modelIndex = combo.model().index(index)

请注意,只有满足以下要求才有效:

  • 您正在使用一个仅基于其行返回 QModelIndex 的模型;
  • 参考列始终是第一列(参见
    QComboBox.setModelColumn()
  • 模型是二维的,并且组合不使用子元素的根索引(考虑像 QFileSystemModel 这样的树模型);

上面的更合适的语法应该如下,它应该适用于任何模型以及使用模型的不同列和根索引的任何情况:

    def getModelIndex(self, index, combo):
        modelIndex = combo.model().index(
            index, combo.modelColumn(), combo.rootIndex())

请注意,如果您只需要访问模型数据并且模型正确实现了

ItemDataRole
枚举,则可以仅使用
itemData()
函数:

    def getComboData(self, index):
        data = combo.itemData(index, SomeRole)
© www.soinside.com 2019 - 2024. All rights reserved.