C++ 如何在 Qt 中创建一个粗体的红色文本标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1464591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:05:04  来源:igfitidea点击:

How to create a bold, red text label in Qt?

c++qttextrichtext

提问by bastibe

I want to write a single, bold red line in my application using Qt.

我想使用 Qt 在我的应用程序中编写一条粗体红线。

As far as I understand, I would create a QLabel, set its textFormat to rich text and give it a rich text string to display:

据我了解,我会创建一个 QLabel,将其 textFormat 设置为富文本并为其提供一个富文本字符串以显示:

QLabel *warning = new QLabel;
warning->setTextFormat(Qt::RichText);
warning->setText("{\rtf1\ansi\ansicpg1252 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green0\blue0;} \f0 \cf0 this is bold red text}");

I tested this rich text string in a rich text editor and it displays fine.

我在富文本编辑器中测试了这个富文本字符串,它显示正常。

But Qt displays the whole string with all braces, keywords and backslashes instead of "this is bold red text". What am I doing wrong?

但是 Qt 会显示带有所有大括号、关键字和反斜杠的整个字符串,而不是“这是粗体红色文本”。我究竟做错了什么?

Thank you for your help.

感谢您的帮助。

回答by rpg

Try using HTML formatting: <b><font... etc </b>.

尝试使用 HTML 格式:<b><font... etc </b>.

Qt Designer does it like this: <span style=" font-size:8pt; font-weight:600; color:#aa0000;">TextLabel</span>

Qt Designer 是这样做的: <span style=" font-size:8pt; font-weight:600; color:#aa0000;">TextLabel</span>

回答by code-tinkerer

You can use Qt StyleSheetsand set the styleSheetproperty of QLabel

您可以使用Qt的样式表和设置styleSheet的属性QLabel

warning->setStyleSheet("font-weight: bold; color: red");

Qt supports most CSS styles on its QWidget-derived classes. You don't need to set the text format to Qt::RichTextfor this to work.

Qt 在其QWidget派生类上支持大多数 CSS 样式。您不需要将文本格式设置Qt::RichText为使其工作。

回答by gnud

Qt uses a simple HTML subsetfor formatting.

Qt 使用一个简单的HTML 子集进行格式化。

回答by Ramya B

You can also do it programmatically using the settextfunction. Something like this:

您也可以使用该settext函数以编程方式执行此操作。像这样的东西:

QString labelText = "<P><b><i><font color='#ff0000' font_size=4>";
labelText .append("Text what u want to display");
labelText .append("</font></i></b></P></br>");
QLabel label->setText(labelText);

You can do it in a single line as well.

您也可以在一行中完成。