我正在尝试创建一个 QTreeWidget,它对除最后一个选择之外的所有选择使用单一突出显示颜色。
我可以使用 QTreeWidget 中的 setPalette 更改所有颜色,但这仅适用于 QTreeWidget 而不是 QTreeWidgetItems。 QTreeWidgetItems 上没有 setPalette
我什至尝试使用样式表,但它仅适用于 QTreeWidget。这种方法在我的实际代码中有点痛苦,因为我有多个列和分支。目前,在我的代码中注释掉了
我知道我需要一个信号,但要获得选择只是不知道如何以不同的方式突出显示它们
from PySide2 import QtCore
from PySide2 import QtWidgets
from PySide2 import QtGui
class TestDialog(QtWidgets.QDialog):
def __init__(self):
super(TestDialog, self).__init__()
self.setWindowTitle("Test Dialog")
self.setMinimumWidth(200)
self.tree = TreeWidget()
# Change all the highlighted items to the same color
# palette = QtGui.QPalette()
# palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(93, 93, 93))
# self.tree.setPalette(palette)
main_layout = QtWidgets.QVBoxLayout(self)
main_layout.addWidget(self.tree)
colors = ['red', 'green', 'blue', 'purple', 'black']
parent = self.tree
for color in colors:
parent = TreeWidgetItem(parent, color)
self.tree.expandAll()
class TreeWidget(QtWidgets.QTreeWidget):
def __init__(self):
super(TreeWidget, self).__init__()
self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.setIndentation(10)
self.setColumnCount(2)
self.header().resizeSection(1, 28)
self.header().swapSections(1, 0)
self.setHeaderHidden(True)
css = """
QTreeView::item:selected
{
background-color: grey;
}
"""
# self.setStyleSheet(css)
delegate = MyDelegate(None, self)
self.setItemDelegate(delegate)
class TreeWidgetItem(QtWidgets.QTreeWidgetItem):
def __init__(self, parent, label):
super(TreeWidgetItem, self).__init__(parent)
self.setText(0, label)
self.lockBox_cb = QtWidgets.QCheckBox()
self.treeWidget().setItemWidget(self, 1, self.lockBox_cb)
class MyDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, parent, tree):
super(MyDelegate, self).__init__(parent)
self.tree = tree
def paint(self, painter, option, index):
column = index.column()
row = index.row()
item = self.tree.itemFromIndex(index)
currentItem = self.tree.currentItem()
brush = QtGui.QBrush(QtCore.Qt.transparent)
painter.setBrush(brush)
painter.fillRect(option.rect, brush)
if column == 0:
if option.state & QtWidgets.QStyle.State_Selected:
if id(currentItem) == id(item):
brush = QtGui.QBrush(QtGui.QColor(102, 40, 178, 255))
else:
brush = QtGui.QBrush(QtGui.QColor(226, 131, 255, 255))
option.palette.setBrush(QtGui.QPalette.Highlight, brush)
option_copy = QtWidgets.QStyleOptionViewItem(option)
option_copy.rect.setLeft(0)
option_copy.backgroundBrush = brush
self.tree.style().drawPrimitive(QtWidgets.QStyle.PE_PanelItemViewItem, option_copy, painter)
super(MyDelegate, self).paint(painter, option, index)
if __name__ == "__main__":
d = TestDialog()
d.show()
我更新了代码以反映我的众多尝试之一。结果总是一样的。在进行其他选择后,颜色确实会发生变化,但部分显示旧颜色,直到我单击不同的 UI。只有这样,颜色才填满整行
GUI刷新后,颜色就正确了
它的分支颜色没有改变。如果您使用样式表并将其设置为背景颜色,您将不会在项目本身之外出现突出显示。这对我有用。
例如:
QTreeView::branch {
background-color: grey;
}