TableView单元格代表(Qt.BackgroundRole)

时间:2012-10-29 11:46:56

标签: python pyqt pyqt4

我正在努力寻找一个看似简单的代表工作。

我想要的是改变tableview单元格的背景。据我所知 我应该看看Qt.BackgroundRole。到目前为止,我还没有能够使它工作,或找到一个相关的例子。

到目前为止,我是一个用颜色填充单元格的代表,但它似乎正在进行中 在文本之上。我想要的是要保留的文本,以及仅更改单元格的背景。

class CellBackgroundColor(QtGui.QStyledItemDelegate):

    def __init__(self, parent = None):
        QtGui.QStyledItemDelegate.__init__(self, parent)

    def paint(self, painter, option, index):       

        path = index.model().data(index,  QtCore.Qt.DisplayRole).toString()
        painter.fillRect(option.rect, QtGui.QColor(path))

关于如何在tableview委托中实现此Qt​​.BackgroundRole的任何想法?

提前致谢, 克里斯

1 个答案:

答案 0 :(得分:2)

您不需要使用委托来绘制单元格背景;默认委托支持通过Qt.BackgroundRole进行背景绘制:

class MyTableModel(QtCore.QAbstractTableModel):
    ...
    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.BackgroundRole:
            return QtGui.QColor(...)

否则,最好使用initStyleOption初始化QStyleOptionViewItem并使用任何适当的覆盖进行绘制:

class CellBackgroundColor(QtGui.QStyledItemDelegate):
    ...
    def paint(self, painter, option, index):
        self.initStyleOption(option, index)
        # override background
        option.backgroundBrush = QtGui.QColor(...)
        widget = option.widget
        style = widget.style()
        style.drawControl(QtGui.QStyle.CE_ItemViewItem, option, painter, widget)