【发布时间】:2021-01-28 14:58:55
【问题描述】:
我编写了一个带有两个 QListWidgets 的小型 PyQt5 应用程序,如图所示。我已经设置了“融合”样式以获取具有背景颜色的组合框,并且作为一个不受欢迎的结果,我遇到了 QListWidget 选择颜色的问题:当它有焦点时,选择有蓝色背景,这非常好,但是会变亮列表失去焦点时的灰色背景(如左侧列表所示),使其难以阅读。
我基于 QTableWidgets 的类似 sn-ps 在小部件上尝试了不同的 CSS 样式组合,但没有成功。
知道如何更改此背景颜色吗?
编辑:鉴于提议的解决方案不起作用,我已经针对您的测试寻找可能的差异。这可能是由于使用了我从 How to display partially bold text in QListWidgetItem with QtCore.Qt.UserRole 获得的自定义 QStyledItemDelegate
from PyQt5 import QtCore, QtGui, QtWidgets
class HTMLDelegate(QtWidgets.QStyledItemDelegate):
'''
The roles >= Qt::UserRole are not used by Qt by default so it can be used for any purpose,
for example to save additional information, in this case it is not the solution.
One possible solution is to use a delegate to render the HTML.
(Extracted from https://stackoverflow.com/questions/53569768/how-to-display-partially-bold-text-in-qlistwidgetitem-with-qtcore-qt-userrole)
'''
def __init__(self, parent=None):
super(HTMLDelegate, self).__init__(parent)
self.doc = QtGui.QTextDocument(self)
def paint(self, painter, option, index):
painter.save()
options = QtWidgets.QStyleOptionViewItem(option)
self.initStyleOption(options, index)
self.doc.setHtml(options.text)
options.text = ""
style = QtWidgets.QApplication.style() if options.widget is None \
else options.widget.style()
style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)
ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
if option.state & QtWidgets.QStyle.State_Selected:
ctx.palette.setColor(QtGui.QPalette.Text, option.palette.color(
QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
else:
ctx.palette.setColor(QtGui.QPalette.Text, option.palette.color(
QtGui.QPalette.Active, QtGui.QPalette.Text))
textRect = style.subElementRect(QtWidgets.QStyle.SE_ItemViewItemText, options, None)
if index.column() != 0:
textRect.adjust(5, 0, 0, 0)
constant = 4
margin = (option.rect.height() - options.fontMetrics.height()) // 2
margin = margin - constant
textRect.setTop(textRect.top() + margin)
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
self.doc.documentLayout().draw(painter, ctx)
painter.restore()
def sizeHint(self, option, index):
return QtCore.QSize(self.doc.idealWidth(), self.doc.size().height())
因此,我想我应该修改为 QPalette 设置颜色的部分。尽管如此,这里没有使用 QStyle::State_HasFocus,所以我不明白为什么它不起作用。现在知道如何解决了吗?
作为一个并行问题:QT 小部件及其子元素的所有 CSS 可能性的定义在哪里?我希望能够自己探索它,而不是在将来用这种简单的 CSS 代码问题来打扰 stackoverflow 用户:)
【问题讨论】:
-
您还可以在 if 语句中与
& QtWidgets.QStyle.State_Active进行比较,这样至少非活动的选定文本不会是白色的。我现在会尝试一些事情。同时这里是style sheets ref
标签: python pyqt pyqt5 qlistwidget qlistwidgetitem