Make QLabel text selectable?

I have a QLabel in my application that displays error messages to the user. I would like to make the text of the label selectable so users can copy and paste the error message if needed.

However, when I use the mouse to click and drag over the text, nothing happens - the text is not selected.

How can I make the text within a QLabel selectable by the mouse?


Solution 1:

Code

The text of a QLabel can be made selectable by mouse like so:

label->setTextInteractionFlags(Qt::TextSelectableByMouse);

This is found in the QLabel documentation.

You can use that same function to make links selectable by keyboard, highlight URL links, and make the text editable. See Qt::TextInteractionFlag.

Designer

Search for textInteractionFlags under the QLabel menu and set the flag TextSelectableByMouse.

Solution 2:

Here is another method, for reference... You could create a QLineEdit subclass instead, tweaked to look and act like a QLabel, in the constructor:

 setReadOnly(true);
 setFrame(false);
 QPalette palette = this->palette();
 palette.setColor(QPalette::Base, palette.color(QPalette::Background));
 setPalette(palette);

I think the accepted answer is simpler and preferable to this though.