QLabel无法完成您想要的事情. QLabel旨在容纳基本文本标签-它的HTML支持相当…绳索.
但是,您可以使用QTextEdit&另外,QTextDocument.
尝试这样的事情(我是从内存中写出来的,因此它可能无法编译或100%正确):
QTextDocument *doc = new QTextDocument(this);
doc->setDefaultStyleSheet("h3 { font-color: red; }");
QTextEdit *edit = new QTextEdit(this);
edit->setDocument(doc);
edit->setHTML("this is a red
heading
");重要的是使用QTextDocument,它允许您更改HTML样式表.从QT文档中:
The default style sheet is applied to all newly HTML formatted text that is inserted into the document, for example using setHtml() or QTextCursor::insertHtml().
The style sheet needs to be compliant to CSS 2.1 syntax.
Note: Changing the default style sheet does not have any effect to the existing content of the document.
编辑:
要获取默认样式表,可以调用QTextDocument :: DefaultStyleSheet()-但是,这仅适用于QTextDocuments,并且可能适用于或可能不适用于所有Qt控件(包括QLabel).