4
votes

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;
    
2
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
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
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

2 Answers

3
votes

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.

0
votes

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