如何使用样式表自定义 QLabels 中链接的外观?
我有一个带有设置深色背景的 Qt 样式表的 QLabel
:
QLabel {
background: black;
color: white;
}
这工作正常,直到我添加带有嵌入 URL 的文本并将 Qt::TextFormat
设置为 Qt::RichText
。该链接显示为默认的深蓝色,在深色背景下很难阅读。
我尝试通过样式表自定义它,例如:
a { color: white; }
QLabel!visited { color: white; }
但这没有任何效果。似乎确实有效的一件事是更改应用程序的 QPalette:
QPalette newPal(qApp->palette());
newPal.setColor(QPalette::Link, Qt::white);
newPal.setColor(QPalette::LinkVisited, Qt::white);
qApp->setPalette(newPal);
但这需要对颜色进行硬编码。有什么方法可以从样式表中设置颜色吗?
编辑:
我发现自定义调色板的另一个问题。如果我只想修改小部件的调色板(在上面的示例中用 widget
替换 qApp
),那么这是行不通的。我不想影响应用程序中的所有其他 QLabels
,那么如何限制对此小部件的调色板更改?
I have a QLabel
with a Qt stylesheet that sets a dark background:
QLabel {
background: black;
color: white;
}
This works fine until I add text with an embedded URL and set the Qt::TextFormat
to Qt::RichText
. The link displays as the default dark blue, which is hard to read on a dark background.
I've tried customising it via a stylesheet such as:
a { color: white; }
QLabel!visited { color: white; }
but this doesn't have any effect. The one thing that does seem to work is changing the application's QPalette
:
QPalette newPal(qApp->palette());
newPal.setColor(QPalette::Link, Qt::white);
newPal.setColor(QPalette::LinkVisited, Qt::white);
qApp->setPalette(newPal);
However this requires the colour to be hardcoded. Is there any way I can set the colour from a stylesheet instead?
EDIT:
I've discovered a further problem with customising the palette. If I want to just modify the palette of my widget (substituting widget
for qApp
in the sample above) then this doesn't work. I don't want to affect all the other QLabels
in the app, so how do I limit the palette changes to this widget?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种方法是将
style="color:whatever"
或类添加到链接的内部中。我还没有弄清楚如何将其应用到整个应用程序,但这是一个好的开始。
One way is to add
style="color: whatever"
or a class to the inner<span>
of the link. I haven't figured out yet how to apply this to the whole application but it's a good start.我在显式设置 QPalette 方面几乎没有取得什么成功——如果您为整个应用程序设置它,它会起作用,但如果您在小部件中设置它,则不起作用。最后,我需要做的最简单的事情是使用 QTextBrowser 相反,它支持 HTML 的子集。然后我可以使用常规 CSS 样式表覆盖链接的颜色:
I've had little success explicitly setting the
QPalette
-- it works if you set it for the entire application, but not if you set it in the widget. In the end though, the easiest thing for what I needed to do was use a QTextBrowser instead which supports a subset of HTML. I could then override the colour of links using a regular CSS stylesheet:简短的回答是否定的。最近我不得不这样做。
QLabel!visited
不起作用,因为 Qt 不跟踪 QLabel 是否被访问。QLabel { color: ... }
不适用于链接。找不到原因,但我发现的只是在这种情况下使用QPallete
的建议。Short answer is no. Recently I had to do this.
QLabel!visited
doesn't work because Qt doesn't track whether QLabel were visited or not.QLabel { color: ... }
doesn't work for links. Can't find why but all I found is a suggestion to useQPallete
in this case.您可以将 HTML 中的颜色标签设置为
You can set the color tag in the HTML to