Unsolved Can not send keyPressEvent to qml
-
Hello,
I am using a QQuickWindow, QQuickRenderControl and a QOffscreenSurface to render a Qml scene into an OpenGL framebuffer object.For this reason , I am using qt example Qt/Examples/Qt-5.15.2/quick/rendercontrol as a base with some minor modifications.
Since no window is actually created, it becomes necessary to artificially transfer mouse and keyboard events to QQuickWindow.There was already mousePressEvent example for mouseEvents on renderControl example which works fine that means I can send mouse events to qml.
Similarly , I tried to implement keyPressEvent and keyReleaseEvent by using QCoreApplication::sendEvent(m_quickWindow, e); function call but it does not send key events to qml even if I set force to true for a rectangle. When I debug the issue , I have observed that activeFocusItem is NULL on qquickwindow.cpp ==> deliverKeyEvent function.
After that , I put a mousearea inside rectangle and call forceActiveFocus() function for rectangle and then keyPressEvent are sent to qml succesfully.Also, If I put timer and call forceActiveFocus for rectangle on some interval it also works but If I try to call same forceActiveFocus() function on Component.onCompleted it is not sending any key events to qml.
So Do I have to call forceActiveFocus() to manage key sending for offscreen surface ? Also if I have to call forceActiveFocus() from qml , then is there any way to call it instead of timer or mousearea ?
Following is my code snippets:
import QtQuick 2.5
import QtQuick.Window 2.2Rectangle {
visible: true
width: 1280
height: 480
color: "#000"Rectangle { id:keyPressRect width:100 height: 100 //focus: true color: activeFocus? "red": "blue" onFocusChanged: console.log("focus changed to: " + focus) onActiveFocusChanged: console.log("active focus changed to: " +activeFocus) Component.onCompleted: { console.log("onCompleted(), focus: " + focus + " activeFocus: " + activeFocus) forceActiveFocus() console.log("onCompleted(), focus: " + focus + " activeFocus: " + activeFocus) } /*Component.onCompleted: mTimer.start() Timer { id:mTimer interval: 5000 repeat: false onTriggered: { keyPressRect.forceActiveFocus() console.log("testtt") } }*/ Keys.onPressed: { console.log("key pressed on qml") } Keys.onReleased: { console.log("key released on qml") } MouseArea { anchors.fill: parent onClicked: { parent.forceActiveFocus() console.log("mouse clicked") } } }
}
and sending keyPressEvent from c++ as the following:
void WindowSingleThreaded::keyPressEvent(QKeyEvent *e)
{
qDebug() << "key press event from cpp";
qDebug() << e->key() << "key is";
QCoreApplication::sendEvent(m_quickWindow, e);
}Any idea is well appreciated.
Best Regards