Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate mouse event with Qt?

Tags:

c++

mouseevent

qt

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;
    
like image 378
Tairy Avatar asked Oct 21 '22 18:10

Tairy


1 Answers

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.

like image 117
Marek R Avatar answered Nov 01 '22 13:11

Marek R