Results 1 to 2 of 2

Thread: Clickable text in custom widget

  1. #1
    Join Date
    Mar 2020
    Posts
    1
    Platforms
    Unix/X11

    Default Clickable text in custom widget

    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

  2. #2
    Join Date
    Jan 2008
    Location
    Alameda, CA, USA
    Posts
    5,240
    Thanks
    303
    Thanked 865 Times in 852 Posts
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Clickable text in custom widget

    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, 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.
    <=== The Great Pumpkin says ===>
    Please use CODE tags when posting source code so it is more readable. Click "Go Advanced" and then the "#" icon to insert the tags. Paste your code between them.

Similar Threads

  1. Replies: 2
    Last Post: 25th September 2014, 01:24
  2. Replies: 0
    Last Post: 19th March 2012, 19:09
  3. Replies: 1
    Last Post: 23rd June 2011, 23:09
  4. How to make a custom qwidget clickable ?
    By ada10 in forum Newbie
    Replies: 2
    Last Post: 1st September 2010, 12:55
  5. Clickable text?
    By hkvm in forum Qt Programming
    Replies: 2
    Last Post: 27th September 2008, 21:49

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.