本文介绍了如何从 qml Keys.onPressed 调用 qt keyPressEvent(QKeyEvent *event)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有

Keys.onPressed {
}

我有一个 C++ 类,它有

And I have a c++ class which has

protected:
    void keyPressEvent(QKeyEvent *event);

Keys.onPressed 里面需要什么?我试过了

What needs to go inside the Keys.onPressed? I have tried

myclass.keyPressEvent(event)

并且我在我的 C++ 类中尝试了一个 public Q_INVOKABLE 函数(handleKeyPress),我想从中调用 keyPressEvent 的参数(QKeyEvent * 事件).

and I have tried a public Q_INVOKABLE function (handleKeyPress) in my c++ class with parameter (QKeyEvent * event) from which I wanted to call the keyPressEvent.

在运行时前者给出

"TypeError: 对象 myclass 的属性 'keyPressEvent' 不是一个函数"

后者

错误:未知方法参数类型:QKeyEvent*".

(然后我发现 qml 只能处理指向 QObject 的指针,而 QKeyEvent 不是从 QObject 继承的,但这并不能帮助我找到解决方案.)

(I have then found out that qml can only handle pointers to QObject, and QKeyEvent doesn't inherit from QObject but that doesn't help me in finding a solution.)

那么从qml 调用keyPressEvent 的正确方法是什么?或者,如果这完全是错误的方法,如果我的班级需要 QKeyEvent 可以给我的信息,例如按下了哪个键等,那么正确的方法是什么?

So what is the correct way to get the keyPressEvent called from qml? Or if this is the wrong approach altogether, what is the correct one if my class needs the information QKeyEvent can give me like which key was pressed etc.?

推荐答案

KeyEvent 不是 QKeyEvent *,而是继承自 QObject 的类code>并封装了一个QKeyEvent,所以QKeyEvent是不能访问的,但是可以访问q-properties如下图:

KeyEvent is not a QKeyEvent *, but a class that inherits from QObject and encapsulates a QKeyEvent, so QKeyEvent can not be accessed, but you could access the q-properties as shown below:

C++

protected:
    Q_INVOKABLE void someMethod(QObject *event){
        qDebug()<< "key" << event->property("key").toInt();
        qDebug()<< "text" << event->property("text").toString();
        qDebug()<< "modifiers" << event->property("modifiers").toInt();
        qDebug()<< "isAutoRepeat" << event->property("isAutoRepeat").toBool();
        qDebug()<< "count" << event->property("count").toInt();
        qDebug()<< "nativeScanCode" << event->property("nativeScanCode").value<quint32>();
        qDebug()<< "accepted" << event->property("accepted").toBool();
    }

QML:

Keys.onPressed: myclass_obj.someMethod(event)

但不建议这样做.你的类不应该直接知道事件,但最好的是你在 QML 中处理逻辑和函数:


But that is not recommended. Your class should not know the event directly, but the best thing is that you handle the logic in QML and that the function:

Keys.onPressed: {
    if(event.key === Qt.Key_A){
        myclass_obj.foo_A()
    }
    else if(event.key === Qt.Key_B){
        myclass_obj.foo_B()
    }
}

或者如果你只想知道密钥可以如下


Or if you want to know only the key could be as follows

C++

Q_INVOKABLE void someMethod(int key){
    qDebug()<< key;
}

QML

Keys.onPressed: myclass_obj.someMethod(event.key)

这篇关于如何从 qml Keys.onPressed 调用 qt keyPressEvent(QKeyEvent *event)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 17:58