QML 程序如何发送模拟键盘消息
[static] bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)
receiver为 engine.rootObjects().at(0)
#ifndef KEYCONTROLLER_H
#define KEYCONTROLLER_H
#include <QObject>
#include <QCoreApplication>
#include <QKeyEvent>
class KeyController : public QObject
{
Q_OBJECT
public:
static KeyController* getInstance()
{
static KeyController controller;
return &controller;
}
void setMianWindow(QObject *win){m_mainWin = win;}
public slots:
void receiveEvent(int k)
{
switch (k) {
default:
{
QKeyEvent key(QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier);
QCoreApplication::sendEvent(m_mainWin,&key);
}
}
};
private:
KeyController()
{
}
QObject *m_mainWin;
};
#endif // KEYCONTROLLER_H
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtDebug>
#include "keycontroller.h"
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qDebug()<<"QQmlApplicationEngine engine;-------------------"<<engine.rootObjects();
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
qDebug()<<"engine.load(url); -------------------"<<engine.rootObjects();
//
KeyController::getInstance()->setMianWindow(engine.rootObjects().at(0));
return app.exec();
}
思路来源
https://stackoverflow.com/questions/48459492/send-keyboard-event-to-qml-application