How Do I Use A QStyledItemDelegate To Paint Only The Background, Without Covering The Text?
How should I change just the background color of my tree item using a delegate? I haven't been able to figure out how to do this without painting on top of the text. In other words
Solution 1:
To override background color for selected items, you can disable the selected flag in initStyleOption
. For example:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class SelectionColorDelegate(QStyledItemDelegate):
def __init__(self, parent):
super(SelectionColorDelegate, self).__init__(parent)
def initStyleOption(self, option, index):
# let the base class initStyleOption fill option with the default values
super(SelectionColorDelegate,self).initStyleOption(option, index)
# override what you need to change in option
if option.state & QStyle.State_Selected:
option.state &= ~ QStyle.State_Selected
option.backgroundBrush = QBrush(QColor(100, 200, 100, 200))
if __name__ == "__main__":
app = QApplication(sys.argv)
treeWidget = QTreeWidget()
treeWidget.setColumnCount(2)
for i in range(5):
item = QTreeWidgetItem(["Item %d"%i, "data" ])
treeWidget.addTopLevelItem(item)
for j in range(3):
subItem = QTreeWidgetItem(["SubItem %d, %d"%(i,j), "subdata"])
item.addChild(subItem)
treeWidget.expandItem(item)
treeWidget.setItemDelegate(SelectionColorDelegate(treeWidget))
treeWidget.show()
app.exec_()
sys.exit()
Apparently, the background is also painted by QTreeView.drawRow
before the delegate paint
function is called, so for indented items, a part of that background keeps the default color.
Post a Comment for "How Do I Use A QStyledItemDelegate To Paint Only The Background, Without Covering The Text?"