6

I want to simulation mouse event with Qt. For example, when I press one key on the keyboard, the program can simulate a mouse click event. I have tried the code below, but when I press 'K', the program stops and gives me an error:

The program has unexpectedly finished.

 case Qt::Key_K:
 QMouseEvent *mEvnPress;
 QMouseEvent *mEvnRelease;
 mEvnPress = new QMouseEvent(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
 mEvnRelease = new QMouseEvent(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
 QCoreApplication::sendEvent(QWidget::focusWidget(),mEvnPress);
 QCoreApplication::sendEvent(QWidget::focusWidget(),mEvnRelease);
 break;
 

László Papp
53.5k40 gold badges118 silver badges142 bronze badges
asked Dec 15, 2013 at 8:01
3
  • Is there more to go with that error? Is it a crash? What happens when you run it with a debugger or QtCreator? Does it stop at a certain line? Commented Dec 15, 2013 at 8:29
  • It can run normally and show the mainwindow in qtcreator.And there is no more output without 'The program has unexpectedly finished.' when I press the key 'K',and the mainwindow display as well. Commented Dec 15, 2013 at 8:54
  • The first parameter to sendEvent seems odd.. You are sending the event to the widget that was last focused. Could focusWidget return NULL? Maybe you should try sending it to the main window and see if that works. Commented Dec 15, 2013 at 9:03

2 Answers 2

3

there is QtTestLib. It is designed for writing test and it has mouseClick which does what you want.

If you don't want to use this module you can always check its source code and see how to properly simulate mouse events.

answered Dec 15, 2013 at 9:13
Sign up to request clarification or add additional context in comments.

Comments

0

You have to use the QtestEventList class. Add event with addmouseclick then simulate.

jadhachem
1,1232 gold badges11 silver badges19 bronze badges
answered Jun 4, 2015 at 21:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.