3

I'm developing a Qt application and I'm trying to implement this feature where if you type a word all it's occurences in a QLabel get highlighted. I'm not sure how to do it. Is there a way for iterate through text in QLabel and change the background colour of certain word?

It can be done using in QTextEdit by using QTextEdit::ExtraSelection. But QLabel doesn't have this method.

So for example if the searched word is "sed" I want to get something like this in my QLabel:

enter image description here

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
madasionka
  • 812
  • 2
  • 10
  • 29

1 Answers1

2

You can use Qt rich text to add some style to the subtext. You will need to search for it yourself in the text string and insert some HTML.

This is my <span style="background-color:yellow">text</span>

An example to highlight a word into existing label (already containing the text) :

QString searchedWord = "sed";

QString txt = lbl->text();
txt.replace(QRegExp("\\b" + searchedWord + "\\b"),
            "<span style=\"background-color:yellow\">" + searchedWord + "</span>");
lbl->setText(txt);

If you want to highlight more than one word, you will need to make a more specific RegExp.

ymoreau
  • 3,402
  • 1
  • 22
  • 60