PDA

View Full Version : Clickable text in custom widget



wmdanor
31st March 2020, 15:50
Is is possible to make text clickable and emit signal if clicked in custom widget?
Or may be at least make clickable area?

e.g.

Some text
Some text
CLICKABLE TEXT
Some text

d_stranz
31st March 2020, 21:13
If you use a QLabel for your text, you can set the focus policy to Qt::ClickFocus. It should then receive mouse press events.

You can derive a new class from QLabel, override mousePressEvent() / mouseReleaseEvent() (to detect clicks), and add a signal that you emit when you have detected a click (mouse down / mouse up inside the label).

Or, you can use QLabel and add an event filter to your custom widget and look for the mouse events coming it. Your custom widget would emit the signal in that case.

If you plan to have multiple instances of this type of label in your UI, I would probably derive a "ClickableLabel" class from QLabel. Someone has done that here (https://wiki.qt.io/Clickable_QLabel), but not quite correctly. The code should really be checking for a mouse pressed / mouse released pair before firing the clicked() signal. So add a handler for the mouseReleaseEvent. In the mousePressEvent, set a "bool mousePressed" member variable flag to true, and in the mouseReleaseEvent handler, check the flag, and if true, then emit the clicked() signal and set the flag back to false.

The reason for looking for the press / release pair is that it allows an "escape" mechanism - if the user presses the button, then changes his mind, he can move off the text and release the mouse. Nothing happens then. If you emit the signal as soon as the mouse goes down, then there is no way for the user to cancel the action.