如何使StyledItemDelegate使用默认选择样式绘制? [英] how to make StyledItemDelegate draw with default selection style?

查看:0
本文介绍了如何使StyledItemDelegate使用默认选择样式绘制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

非常感谢您的帮助!

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

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)

这篇关于如何使StyledItemDelegate使用默认选择样式绘制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆