在QStyledItemDelegate中显示QComboBox文本而不是索引值

时间:2010-08-25 17:00:02

标签: python pyqt pyqt4

所以我有一个模型,其中一个列包含一个国家/地区。但是,因为我想显示一个组合框以从选项列表中选择国家/地区,所以我不会直接在模型中存储国家/地区名称。相反,我将索引值存储到允许的国家/地区列表中。这允许我在Qt文档中建议的表单视图中使用QComboBox。问题是我也有一个表视图,表视图显示索引整数,而不是国家名称。我设置了QStyledItemDelegate并实施了createEditor,因此,如果您点击世界单元格,它会弹出ComboBox,但是当您不编辑国家/地区时,您会看到索引值

我是解决方案的一部分。我已经实现了一个绘制方法来完成工作,但它正在显示值偏移到它的正确位置,我无法弄清楚如何让它正确显示。我认为渲染方法中的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 个答案:

答案 0 :(得分:4)

模型对于不同的数据有不同的item data roles。有Qt::DisplayRoleQt::EditRoleQt::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::EditRole,这非常适用于此目的。如果您随后使用本机类型作为显示角色,则不需要进行任何自定义绘制,但如果您愿意,可以使用。

相关问题