【问题标题】:Passing event.key from childs to parent in qml在qml中将event.key从孩子传递给父母
【发布时间】:2018-04-17 16:33:01
【问题描述】:

我将尝试用一个简单的例子来说明我的问题。

我有一个看起来像这样的主窗口:

Item {
    id: root
    LW { id: leftWindow }
    RW { id: rightWindow }
}

leftWindowrightWindowWindow 组件,它们看起来像:

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,但我已经尝试过了,并没有真正传播到根元素。

如何做到这一点?

【问题讨论】:

  • 我只是偶然注意到你的更新,因为我已经给出了答案,所以我必须更新它。

标签: qt qml


【解决方案1】:

你可以在根Item中定义一个信号

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的同时,可以在主Item中实现Keys处理程序并从Window接收事件:

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)
        }
...
}

更新:基于有问题的编辑

根据Keyboard Focus in Qt Quick, 事件的传播发生在QQuickItem 层次结构中,在活动的QQuickWindow 内...直到QQuickItem 接受关键事件

  1. 如果到达根项,则忽略键事件。

传播发生在Item继承属性链Difference in QML between Window and Item in parent-children relationship

这意味着QQuickWindow 不处理也不传播该事件,就像在这篇文章QML2 ApplicationWindow Keys handling 中一样

因此Window 作为最高父级将忽略该事件并且不会进一步传播到Item。解决方法是手动转发事件,要么完全Keys.forwardTo: [root],要么操作并转发。

【讨论】:

  • 我会测试并报告
猜你喜欢
  • 2020-07-22
  • 1970-01-01
  • 2018-06-29
  • 2013-03-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
相关资源
最近更新 更多