Getting position of mouse click in a QLabel

后端 未结 2 1395
别跟我提以往
别跟我提以往 2020-12-12 07:30

What is the best (as in simplest) way to obtain the pos of a mousePressedEvent in a QLabel? (Or basically just obtain the location of a mouse click

相关标签:
2条回答
  • 2020-12-12 07:57

    I had the same problem

    invalid static_cast...

    I just forgot to include the header: #include "qevent.h"

    Now everything is working well.

    0 讨论(0)
  • 2020-12-12 08:20

    You could subclass QLabel and reimplement mousePressEvent(QMouseEvent*). Or use an event filter:

    bool OneOfMyClasses::eventFilter( QObject* watched, QEvent* event ) {
        if ( watched != label )
            return false;
        if ( event->type() != QEvent::MouseButtonPress )
            return false;
        const QMouseEvent* const me = static_cast<const QMouseEvent*>( event );
        //might want to check the buttons here
        const QPoint p = me->pos(); //...or ->globalPos();
        ...
        return false;
    }
    
    
    label->installEventFilter( watcher ); // watcher is the OneOfMyClasses instance supposed to do the filtering.
    

    The advantage of event filtering is that is more flexible and doesn't require subclassing. But if you need custom behavior as a result of the received event anyway or already have a subclass, its more straightforward to just reimplement fooEvent().

    0 讨论(0)
提交回复
热议问题