0

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 relative to a QLabel widget)

EDIT

I tried what Frank suggested in this way:

bool MainWindow::eventFilter(QObject *someOb, QEvent *ev)
{
if(someOb == ui->label && ev->type() == QEvent::MouseButtonPress)
{
    QMouseEvent *me = static_cast<QMouseEvent *>(ev);
    QPoint coordinates = me->pos();
    //do stuff
    return true;
}
else return false;
}

However, I receive the compile error invalid static_cast from type 'QEvent*' to type 'const QMouseEvent*' on the line where I try to declare me. Any ideas what I'm doing wrong here?

Jonas
  • 121,568
  • 97
  • 310
  • 388
wrongusername
  • 18,564
  • 40
  • 130
  • 214

2 Answers2

9

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().

Frank Osterfeld
  • 24,815
  • 5
  • 58
  • 70
  • Do you really need 2 `const`'s in the declaration of me? If so, why? Also, I am having trouble compiling your code as the compiler gives me `invalid static_cast from type 'QEvent*' to type 'const QMouseEvent*'` on that line – wrongusername Dec 04 '10 at 19:02
  • Did you include ? The consts are not strictly necessary, but I consider it good practice to make temporaries const. – Frank Osterfeld Dec 04 '10 at 19:52
  • ah yes, I didn't include that. Thanks! What I was wondering though was why it wasn't just `const QMouseEvent * me`... what does the second const do? – wrongusername Dec 04 '10 at 20:10
  • The first const makes the object const, the second makes the pointer itself const. – Frank Osterfeld Dec 09 '10 at 22:10
0

I had the same problem

invalid static_cast...

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

Now everything is working well.

Jawa
  • 2,336
  • 6
  • 34
  • 39
Tim
  • 1