codeofandrin
codeofandrin

Reputation: 1547

Pyqt5: How to format text without using QFont?

Well as the title already tells, I want to simply format a text without using QFont(). At the moment I'm using it like that:

font = QFont()
font.setBold(True)

label = QLabel()
label.setFont(font)
label.setText("Hello World!")

So far so good. But if I want to have a certain part in a text of a label bold, it gets quite annoying, because I have to create an extra QLabel and use setBold() and put this part into the right position. Is there a way (e.g. markdown) to bold a certain part of a text of a label?

Like that:

label = QLabel()
label.setText("**Hello** World!")

Upvotes: 3

Views: 1239

Answers (1)

ypnos
ypnos

Reputation: 52337

Qt uses a subset of HTML for rich text. This is also the default setting. Try:

label.setText("<b>Hello</b> World!")

The label text format is controlled by the textFormat property. The default is Auto, for possible values see https://doc.qt.io/qt-5/qt.html#TextFormat-enum.

If you use a recent version of Qt (at least 5.14) you can also use Markdown as you suggested:

label.setTextFormat(Qt.MarkdownText)
label.setText("**Hello** World!")

Reference: https://doc.qt.io/qt-5/richtext-html-subset.html

Upvotes: 5

Related Questions