C++ – How to simulate mouse event with Qt

cmouseeventqt

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;
    

Best Answer

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.

Related Topic