Make QLabel text selectable?

C++Qt

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCory KleinView Question on Stackoverflow
Solution 1 - C++Cory KleinView Answer on Stackoverflow
Solution 2 - C++Don HatchView Answer on Stackoverflow