QT的学习日志 QML如何发送模拟键盘消息

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值