2012-10-29 122 views
1

我努力得到什麼似乎是一個簡單的委託工作。的TableView細胞代表(Qt.BackgroundRole)

我要的是改變的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的任何想法?

由於提前, 克里斯

回答

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) 
+0

嗨ecatmur,非常感謝您回覆。你在第二個例子中究竟如何覆蓋背景? – user1028826

+0

@ user1028826您可以設置'backgroundBrush':http://doc.qt.digia.com/qt/qstyleoptionviewitemv4.html#backgroundBrush-var – ecatmur

+0

非常感謝得到它現在的工作,你的第二個例子完美的作品。歡呼聲有很棒的一週! – user1028826