我需要将悬停和QTreeWidget中所选项目的突出显示颜色设置为无。但我也希望选中或突出显示的项目带有某种边框。
现在我有了这样的QTreeWidget:
项目“ model_1”具有绿色背景色,例如“ model_2”。当我选择或仅将鼠标悬停时,它将变为蓝色,而我看不到原始的背景色。我想查看原始背景色(在本示例中为绿色)。
我尝试用stylesheet来做到这一点:
QTreeView::item:selected {
border: black;
border-radius:5px;
background-color: rgba(0,128,255,100);
}
QTreeView::item:hover {
border: black;
border-radius:1px;
background-color: rgba(0,128,255,95);
}
QTreeView::item:hover:selected {
border: black;
border-radius:1px;
background-color: rgba(0,128,255,70);
}
我尝试设置background-color: inherit;
,但是它不起作用...
如我所见here:
注意:列出的here允许的RGB颜色与CSS 2.1允许的RGB颜色相同。
不支持某些关键字,例如“继承”。
我需要在Linux和Windows上做到这一点。
请帮助。
答案 0 :(得分:0)
我解决了。
self.setStyleSheet(""" QTreeView::item:selected { } QTreeView::item:hover { } QTreeView::item:hover:selected { } """)
class MyStyledItemDelegate(QtWidgets.QStyledItemDelegate): ''' For overriding behavior of selection and hovering in QTreeView and QTreeWidget When you set background color (QtGui.QColor()) to QTreeWidgetItem you also must set this color like: item.setData(0, QtCore.Qt.BackgroundRole, QtGui.QColor()) ''' def paint(self, painter, option, index): def draw_my(option, painter, brush, text, icon): if brush is None: brush = QtGui.QColor(255, 255, 255, 0) # This is original background color. I just set alpha to 0 which means it is transparent x, y = (option.rect.x(), option.rect.y()) h = option.rect.height() painter.save() painter.setFont(option.font) if icon: icon = icon.pixmap(h, h) painter.drawPixmap(QtCore.QRect(x, y, h, h), icon) painter.drawText(option.rect.adjusted(h, 0, 0, 0), QtCore.Qt.AlignLeft, text) else: painter.drawText(option.rect, QtCore.Qt.AlignLeft, text) painter.setCompositionMode(QtGui.QPainter.CompositionMode_SourceAtop) painter.setPen(QtGui.QPen(QtCore.Qt.NoPen)) painter.fillRect(option.rect, brush) painter.setBackgroundMode(QtCore.Qt.OpaqueMode) painter.setBackground(brush) painter.drawRect(option.rect) painter.restore() # Also should be activated in StyleSheet # Selected Hovered if (option.state & QtWidgets.QStyle.State_Selected) or (option.state & QtWidgets.QStyle.State_MouseOver): option.font.setWeight(QtGui.QFont.Bold) brush = index.data(QtCore.Qt.BackgroundRole) text = index.data(QtCore.Qt.DisplayRole) icon = index.data(QtCore.Qt.DecorationRole) draw_my(option=option, painter=painter, brush=brush, text=text, icon=icon) else: QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
QTreeWidget
对象custom_QStyledItemDelegate = MyStyledItemDelegate() tree_widget.setItemDelegate(custom_QStyledItemDelegate)
item.setBackground(0,QtGui.QBrush(QtGui.QColor(0,255,150,100)))
item.setData(0,QtCore.Qt.BackgroundRole,QtGui.QColor(0,255,150, 100))#需要在MyStyledItemDelegate中选择油漆并将其悬停在数据上
PS:对这个答案的样式太糟糕,我感到抱歉,我不明白如何为代码段设置代码样式。。它不起作用。