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;
-
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?sFuller– sFuller2013年12月15日 08:29:41 +00:00Commented 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.Tairy– Tairy2013年12月15日 08:54:27 +00:00Commented 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.sFuller– sFuller2013年12月15日 09:03:35 +00:00Commented Dec 15, 2013 at 9:03
2 Answers 2
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.
Comments
You have to use the QtestEventList class. Add event with addmouseclick then simulate.