Detecting QWidget/QLabel Name on mousePressEvent



  • I am using QT 5.10.11 with VS2015 C++ on a Win10 platform.

    I have a series of qlabels that I want to detect mouse clicks on. I followed some examples like: https://www.youtube.com/watch?v=d0CDMtfefB4 and was actually successful detecting mouse clicks.

    Now, I need to determine which of several qlabels the mouse was clicked on.

    What is the best way of doing that?

    Thanks for any help.


  • Qt Champions 2017

    Use Event filter mechanism for this. Set an object name for each and every label or u can use the text which you set on the label itself. Create one event filter object and set this as filter to every QLabel. Inside the eventFilter(..) function you can get an object name or text of the label.



  • Or subclassing like a YouTube video. like this:

    // in MyLabel.h
    #include <QLabel>
    
    class MyLabel : public QLabel
    {
        Q_OBJECT
    [...]
    ​signals:
    ​    void pressed(const QString &name, const QPoint &pos);
    ​protected:
        virtual void mousePressEvent(QMouseEvent *event) override
    ​    {
            if (event->button() == Qt::LeftButton)
                emit pressed(text(), event->pos());​
    ​    }
    [...]
    };
    
    // in Dialog.cpp
    #include "mylabel.h"
    
    [...]
    for (int i = 0; i < 5; ++i) {
        auto label = new MyLabel(QString("TEST-%1").arg(i));
        connect(label, &MyLabel::pressed, [label](const QString &name, const QPoint &pos){
            qDebug() << label << name << pos;
        });
        [...]
    }
    [...]
    

  • Qt Champions 2017

    Hi
    There is also
    http://doc.qt.io/qt-5/qsignalmapper.html
    for such use case.


  • Moderators

    @mrjj
    just a note: QSignalMapper is deprecated since there is the possibility to connect to lambda slots


  • Qt Champions 2017

    Hi
    Good catched, just noticed
    "This class is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code." :)



  • Thanks all.

    One thing I notice is that using these approaches causes a significant performance hit.
    In my app, I am processing images.
    Before adding the events feature to the QLabel class, I was running at ~15fps.
    After adding this to QLabel, I dropped to ~8fps.
    In most cases, this probably does not matter but it does for me.


  • Qt Champions 2017

    @pistorinoj
    Hi
    Adding a mousePressEvent override should not have any influence
    on how fast it can draw its pixmap.
    I would test again.
    Or you could post teh actual code used and we could have a look.
    Its not normal that it would reduce the "FPS" by 50% since code is only active if u click it.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.