如何使StyledItemDelegate使用默认选择样式绘制?样式、StyledItemDelegate

2023-09-03 10:30:44 作者:桃子不淘/香蕉不娇

我正在使用StyledItemDelegate在QTableView的一个单元格中呈现一个图标。 当一行被选中时,我希望代理的背景像默认项目的背景一样绘制,但不确定如何处理它。 我想答案就在initStyleOption()方法和委托的"选项"之间,但是我自己找不到关于这些选项的全面文档来解决这个问题。

非常感谢您的帮助!

Word2010如何快速修改默认样式

以下是一些示例代码,它显示了自定义委托如何绘制圆形,然后忽略行选择和背景颜色,只保持白色:

import sys
from PySide.QtGui import *
from PySide.QtCore import *


class MyItemDelegate(QStyledItemDelegate):
    def __init__(self, parent=None):
        super(MyItemDelegate, self).__init__(parent)

    def paint(self, painter, option, index):
        if index.column() == 0:
            rect = option.rect
            rect.setWidth(rect.height())
            painter.drawEllipse(rect)
        else:
            QStyledItemDelegate.paint(self, painter, option, index)


class MyModel (QStandardItemModel):
    def __init__( self, parent=None ):
        super( MyModel, self).__init__( parent )
        self.setHorizontalHeaderLabels(['a', 'b', 'c'])
        self.init_data()

    def init_data(self):
        for row in range(0, 5):
            for col in range(0, 3):
                col_item = QStandardItem( '%s' % (row * col) )
                self.setItem(row, col, col_item)

class MyTableView(QTableView):
    def __init__( self, parent=None ):
        super( MyTableView, self).__init__( parent )
        model = MyModel()
        self.setModel(model)
        self.setItemDelegate(MyItemDelegate())
        self.setSelectionBehavior(QAbstractItemView.SelectRows)

if __name__ == '__main__':   
    app = QApplication( sys.argv )
    model = MyModel()
    view = MyTableView()
    view.show()
    sys.exit( app.exec_() )

推荐答案

您应该在进行自己的绘制之前调用基类Paint方法,以保持默认行为:

    def paint(self, painter, option, index):
        QStyledItemDelegate.paint(self, painter, option, index)
        if index.column() == 0:
            rect = option.rect
            rect.setWidth(rect.height())
            painter.drawEllipse(rect)