View Full Version : App crash when using eventFilter

23rd September 2012, 23:57
Hi all

I need to change cursor when my mouse cursor is over rectangle. I tried using eventFilter but my app crash when I try to run it, can you help me with this:

bool MainWindow::eventFilter(QObject *o, QEvent *e){

QMouseEvent *mouseEvent = static_cast<QMouseEvent*>( e );
QPoint pos = mouseEvent->pos();

return QMainWindow::eventFilter(o, e);}

24th September 2012, 00:09
What do you think should happen in the static cast when the QEvent passed in is not a QMouseEvent? You cannot cast a QKeyEvent* to QMouseEvent* and get something meaningful. You should look at the example here.

24th September 2012, 00:19
I don't understand what are you trying to tell me :) What am I doing wrong

24th September 2012, 00:53
The event filter will be called for every event, of any type, sent to the object it is filtering. This means your code will receive QKeyEvent, QResizeEvent, QFocusEvent etc. objects (and lots of them). Casting a QFocusEvent* to QMouseEvent* tells the compiler that you know what you are doing and that it should treat the data structure as a mouse event. If it is not a mouse event accessing the data through that pointer will at best give you safe rubbish and at worst crash the program. The example I linked show how you test for the type of event before you cast the pointer.

In general, anywhere you see static_cast<> you should see danger signs. There are no safety checks other than your own.

You may also want to consider the QWidget::mouse*Event() functions if the screen area you are interested falls within a custom widget.

24th September 2012, 14:56
Now I understand, thank you.