51

I want to write a single, bold red line in my application using 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 *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?

Thank you for your help.

bastibe
  • 16,551
  • 28
  • 95
  • 126

4 Answers4

70

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

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

rpg
  • 7,746
  • 3
  • 38
  • 43
47

You can use Qt StyleSheets and set the styleSheet property of 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::RichText for this to work.

code-tinkerer
  • 509
  • 4
  • 9
  • Answering my own comment: it is becouse first part(title) was in `font` tag with `size` set to relative value and other body wasn't in it... – ephemerr Sep 03 '20 at 13:51
13

Qt uses a simple HTML subset for formatting.

Joshua D. Boyd
  • 4,808
  • 3
  • 29
  • 44
gnud
  • 77,584
  • 5
  • 64
  • 78
1

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

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.

Community
  • 1
  • 1
Ramya B
  • 49
  • 1
  • 6