Qt 在qml中将event.key从child传递给父级
我将用一个简单的例子来说明我的问题 我有一个主窗口,看起来像这样:Qt 在qml中将event.key从child传递给父级,qt,qml,Qt,Qml,我将用一个简单的例子来说明我的问题 我有一个主窗口,看起来像这样: Item { id: root LW { id: leftWindow } RW { id: rightWindow } } leftWindow和rightwindown是Window组件,它们看起来像: Window { id: left width: 1280 height: 320 visible: true Rectangle{ anc
Item {
id: root
LW { id: leftWindow }
RW { id: rightWindow }
}
leftWindow
和rightwindown
是Window
组件,它们看起来像:
Window {
id: left
width: 1280
height: 320
visible: true
Rectangle{
anchors.fill: parent
color: "black"
focus: true
Keys.onPressed: {
if (event.key == Qt.Key_Left) {
event.accepted = true;
}
}
}
}
我想在按下某个键时执行一些操作,而不管此时激活的是哪个窗口。
这意味着我应该以某种方式捕获所有key.event
,并将它们传递给两个窗口的父窗口。
文档中提到,事件将自动向上传播到父级,直到执行event.accepted=true
,但我已经尝试过了,没有任何内容真正传播到根元素
如何做到这一点?您可以在根项中定义一个信号
Item {
id:root
signal activated(real value)
onActivated: console.log("Singal emitted with value: " + value)
LW { id: leftWindow }
RW { id: rightWindow }
}
并在每个活动窗口中发出该信号
Window {
id: left
width: 1280
height: 320
visible: true
Rectangle{
anchors.fill: parent
color: "black"
focus: true
Keys.onPressed: {
if (event.key === Qt.Key_Left) {
event.accepted = true;
onPressed: root.activated(1)
}
}
}
}
要将事件本身转发回根项目,可以在主项目中实现密钥处理程序,并从窗口接收事件:
Item {
id: root
Keys.onPressed: {
if (event.key === Qt.Key_Left){
event.accepted = true;
console.log(event.key)
}
}
LW { id: leftWindow }
RW { id: rightWindow }
}
在窗口中:
Window {
...
// Keys.forwardTo: [root] // Just forward the event, OR action and forward:
Keys.onPressed: {
root.Keys.pressed(event)
}
...
}
更新:基于相关的编辑
根据,,
事件的传播发生在活动的QQuickWindow
中的QQuickItem
层次结构上。。。直到QQuickItem
接受密钥事件
项
继承属性链中
这意味着QQuickWindow
不会处理或传播该事件,正如本文所述
因此,
窗口
作为顶级父级将忽略事件,不会进一步传播到项
。解决方案是手动转发事件,或者完全Keys.forwardTo:[root]
或者操作并转发。我只是偶然注意到您的更新,因为我已经给出了答案,我必须更新它。我将测试并报告