简体   繁体   中英

Post event to Qt GUI thread to simulate key press

I want to simulate key presses in Qt. I have found some examples online, but have not got it working yet. I have this method:

void SimKeyEvent::pressTab()
{
    QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Space, Qt::NoModifier);
    QCoreApplication::postEvent(receiver, event);
}

I don't know how to properly address the GUI thread which should be the 'receiver' in the code lines above. What I have tried is passing the 'app':

QGuiApplication app(argc, argv);

through the SimKeyEvent class constructer and made a private pointer to it.

In main.cpp:

SimKeyEvent *simKeyEvent = new SimKeyEvent(0, &app);

SimKeyEvent.h

private:
    QGuiApplication *app;

SimKeyEvent constructor:

SimKeyEvent::SimKeyEvent(QObject *parent, QGuiApplication *app) :
    QObject(parent)
{
    this->app = app;
}

Then I change to:

QCoreApplication::postEvent(app, event);

This did not work and I don't know if there is something wrong with the code or if its supposed to be done a different way.

main.cpp:

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/GC/MainMenu.qml"));

    SimKeyEvent *simKeyEvent = new SimKeyEvent(0, &app);

    viewer.showExpanded();
    return app.exec();
}

EDIT: I also tried using 'this': QCoreApplication::postEvent(this, event);

See this post for the answer to this question.

Code snippet:

bool MyWidget::event(QEvent *event)
{
     if (event->type() == QEvent::KeyPress) {
         QKeyEvent *ke = static_cast<QKeyEvent *>(event);
         if (ke->key() == Qt::Key_Tab) {
             // special tab handling here
             return true;
         }
     } else if (event->type() == MyCustomEventType) {
         MyCustomEvent *myEvent = static_cast<MyCustomEvent *>(event);
         // custom event handling here
         return true;
     }
     return QWidget::event(event);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM