Reputation: 233
How do I remove the background color of a QTreeWidgetItem
, or reset it to the default?
treeWidgetItem.setBackgroundColor(0, QtGui.QColor('green'))
Upvotes: 5
Views: 13620
Reputation: 120608
The correct method is to clear the underlying data, like this:
treeWidgetItem.setData(0, QtCore.Qt.BackgroundRole, None)
It's worth noting that when a background has not been set, the background()
method will actually return a null QBrush
rather than None
. This because the underlying Qt code does this:
return qvariant_cast<QBrush>(data(column, Qt::BackgroundRole))
So it takes a null QVariant
(which is equivalent to None
, in PyQt terms) and casts it to a null QBrush
- which means it does not represent the default system colours, and cannot be used to reset the original values.
Upvotes: 6
Reputation: 397
You can get the background colour with this:
treeWidgetItem.background(0)
returning something like:
<PySide.QtGui.QBrush(QColor(ARGB 1, 0, 0, 0) , NoBrush ) at 0x00000000EB1F6588>
Now put that into a string before you apply your change and you've got your answer.
originalBG = treeWidgetItem.background(0)
# New background
treeWidgetItem.setBackgroundColor(0, QtGui.QColor('green'))
# Old background
treeWidgetItem.setBackgroundColor(0, originalBG)
Upvotes: 1
Reputation: 409
I successfully removed the background color by setting it to a transparent white.
treeWidgetItem.setBackgroundColor(0, QtGui.QColor(255, 255, 255, 0))
That also works with dark desktop themes.
But since the setBackgroundColor
method is deprecated I now use:
treeWidgetItem.setBackground(0, QtGui.QBrush(QtGui.QColor(255, 255, 255, 0)))
Upvotes: 0
Reputation: 10859
The default value may depend on the OS and other factors.
Since you changed the background color with
treeWidgetItem.setBackgroundColor(0, QtGui.QColor('green'))
you can as well read out the default brush before
default_tree_widget_item_brush = treeWidgetItem.background(column)
and set it back to this later on when you want to return to the default values.
Sidenote: In Qt 5.6 there seems to be no method setBackgroundColor
for QTreeWidgetItems
, only setBackground
. So the solution may depend slightly on the used version of Qt.
Upvotes: 0
Reputation: 2602
I am not sure if there is any way of doing it with setBackgroundColor
, But i would use setStyleSheet
.
Stylesheet's work with every QtGui
widget and are more easier to use overall.
If you want to set the QTreeWidget
background color to green:
self.TreeWidgetItem = QtGui.QTreeWidgetItem()
self.TreeWidgetItem.setStyleSheet("background-color: green;")
If you want to reset the Stylesheet of QTreeWidget, simply type this:
self.TreeWidgetItem.setStyleSheet("")
This would reset any widget's color to default one, without giving any exceptions.
Also it is good practice to use qt stylesheet system, It is easy and has a lot of perks.
Upvotes: 3