TableView单元格委托(背景角色)

2024-09-30 16:40:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想要的是更改tableview单元格的背景。据我所知 我应该看看背景角色. 到目前为止,我还没能让它发挥作用,或者找到一个相关的例子。在

到目前为止,我得到的是一个用颜色填充单元格的代理,但它似乎正在运行 在文本的顶部。我想要的是保留文本,并且只更改单元格的背景。在

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委托中?在

提前谢谢你, 克里斯


Tags: path文本self角色indexinitdef代表
1条回答
网友
1楼 · 发布于 2024-09-30 16:40:14

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

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

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

^{pr2}$

相关问题 更多 >