如何将QKeyEvent发送到特定的qml项目



我正在尝试向QML文件中的项目(如TextField)发送自定义QKeyEvent(如按键B)。这是我写的,但它不起作用。项目(TextField)似乎没有得到我的事件(我假设这是因为没有B字符附加到我的TextField的文本中)。我在ClickHandler类中捕获click信号,然后在handleClick插槽中,我尝试将自定义event发布到我的focused item,在这里是TextField

点击处理程序.h

class ClickHandler : public QObject
{
    Q_OBJECT
    QQmlApplicationEngine* engine;
    QApplication* app;
public:
    explicit ClickHandler(QQmlApplicationEngine *,QApplication* app);
signals:
public slots:
    void handleClick();
};

ClickHandler.cpp:

#include "clickhandler.h"
#include <QMessageBox>
#include <QQuickItem>
ClickHandler::ClickHandler(QQmlApplicationEngine* engine, QApplication* app)
{
    this->engine = engine;
    this->app = app;
}
void ClickHandler::handleClick()
{
    QObject* root = engine->rootObjects()[0];
    QQuickItem *item = (root->property("activeFocusItem")).value<QQuickItem *>();
    if (item == NULL)
        qDebug() << "NO item";
    QKeyEvent* event = new QKeyEvent(QKeyEvent::KeyPress,Qt::Key_B,Qt::NoModifier);
    QCoreApplication::postEvent(item,event);
}

main.cpp:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    QObject* root = engine.rootObjects()[0];
    ClickHandler* ch = new ClickHandler(&engine, &app);
    QQuickItem* button = root->findChild<QQuickItem*>("button");
    QObject::connect(button, SIGNAL(clicked()), ch, SLOT(handleClick()));
    return app.exec();
}

main.qml:

ApplicationWindow {
    objectName: "rootWindow"
    visible: true
    Column {
        TextField {
            id: textId1
            objectName: "text1"
            text: "text1 message"
            focus: true
        }
        TextField {
            id: textId2
            objectName: "text2"
            text: "text2 message"
        }
        Button {
            objectName: "button"
            text : "Click me";
        }
    }
}

如果您实现onPressed处理程序,您可以看到问题所在。

ApplicationWindow {
    objectName: "rootWindow"
    visible: true
    Column {
        TextField {
            id: textId1
            objectName: "text1"
            text: "text1 message"
            focus: true
            Keys.onPressed: {
                console.log("textId1: " + event.key + " : " + event.text)
            }
        }
        TextField {
            id: textId2
            objectName: "text2"
            text: "text2 message"
            Keys.onPressed: {
                if (event.key === Qt.Key_B) {
                    console.log("I like B's but not QString's")
                }
            }
        }
...

此代码打印qml: textId1: 66 :,因为该键的文本为空。

您需要使用以下内容创建事件:

Qt::Key key = Qt::Key_B;
QKeyEvent* event = new QKeyEvent(QKeyEvent::KeyPress,
                                 key,
                                 Qt::NoModifier,
                                 QKeySequence(key).toString());

相关内容

  • 没有找到相关文章

最新更新