代码之家  ›  专栏  ›  技术社区  ›  Simon Hibbs

在qStyledEditMDelegate中显示qcomboBox文本而不是索引值

  •  1
  • Simon Hibbs  · 技术社区  · 16 年前

    所以我有一个模型,其中一列包含一个国家。但是,因为我想显示一个组合框来从选项列表中选择国家,所以我不直接将国家名称存储在模型中。相反,我将索引值存储到允许的国家列表中。这允许我使用 QComboBox 在我的窗体视图中,如qt docs中建议的那样。问题是我还有一个表视图,表视图显示的是索引整数,而不是国家名称。我已经建立了一个 QStyledItemDelegate 并实施 createEditor 所以如果你点击“世界”单元格,它会弹出 ComboBox ,但如果不编辑国家,则会看到索引值。

    我是解决方案的一部分。我已经实现了一个paint方法来完成这项工作,但是它显示的值偏移到了它的正确位置,我不知道如何让它正确显示。我想 option.rect.topLeft() 在渲染方法是错误的,但我不知道如何设置正确的绘图。

    def paint(self, painter, option, index):
        if index.column() == COUNTRY:
            painter.save()
            countryRef, ok = inex.data().toInt()
            countryStr = country_list[countryRef]
            widget = QLineEdit()
            widget.setGeometry(option.rect)
            widget.setText(countryStr)
            widget.render(painter, option.rect.topLeft())
            painter.store()
        else:
            QStylyedItemDelegate.paint(self, painter, option, index)
    
    1 回复  |  直到 10 年前
        1
  •  4
  •   iamantony    11 年前

    模型有不同 item data roles 对于不同的数据。有一个 Qt::DisplayRole , Qt::EditRole 和A Qt::UserRole 在其他中。在本例中,您希望显示与实际数据不同的内容,因此可以添加一个新角色,例如 Qt::UserRole+1 用于索引。

    然后,您希望您的代理在 setModelData :

    def setModelData(self, editor, model, index):
        cbIndex = editor.currentIndex()
        model.setData(index, cbIndex, Qt.UserRole+1)
        # we want a nice displayable though
        model.setData(index, countryIndexToDisplayable(cbIndex), Qt.DisplayRole)
    

    当然,您将以类似的方式检索要在编辑器中设置的数据:

    def setEditorData(self, widget, index):
        widget.setCurrentIndex(index.data(Qt.UserRole+1))
    

    根据您的模型和视图,您可能可以使用 QT::编辑角色 这是为了这个目的。如果您随后使用本地类型作为显示角色,则不需要进行任何自定义绘制,但如果您愿意,也可以这样做。