首页 > 解决方案 > Keys.onPressed 的键盘事件在某些情况下未处理

问题描述

我正在尝试从嵌入式系统上在 linux 下运行的应用程序(使用 Yocto Project 自定义构建)上的 USB 摄像头获取按钮事件。目前我正在使用 Qt 5.6.3。我的问题是,当我通过 SSH 从我的电脑(通过 Qt Creator 和一个简单的 shell)运行代码时,我在下面显示的代码就像一个魅力,但是如果我直接在系统上运行相同的程序而不使用 SSH 什么都没有当我单击相机上的按钮时发生(实际上也不是键盘上的任何其他键)。

按照一些在线示例,我使用了 Keys.onPressed ,然后过滤事件以获得所需的行为。为了在全局范围内获取它,我将事件处理程序直接放在我的 ApplicationWindow 中的 Item 中。

ApplicationWindow {
    Item {
        focus: true
        Keys.onPressed:{
            console.log(event.key)
            playSound.play() //I play a sound to be sure a button is clicked
            if(camera.recording && event.key === 16777466) {
            //do stuff for the right key here            
            }
        }
    }
    //Other elements here
}

我认为这与我系统上运行的 X 服务器有关。但是一切都是默认的,我真的不知道在我的系统中寻找什么来暗示什么不起作用。我真的很感激任何建议。

标签: qtqml

解决方案


经过几个小时的搜索,事实证明这确实是 X 服务器的“活动窗口”的问题,但解决方案非常简单,我只需要添加 requestActivate(); 在我的主要观点上,就像这样:

ApplicationWindow {
    Item {
        focus: true
        Keys.onPressed:{
            console.log(event.key)
            playSound.play() //I play a sound to be sure a button is clicked
            if(camera.recording && event.key === 16777466) {
            //do stuff for the right key here            
            }
        }
    }

    StackView{
        id: rootView
        width: 1280
        height: 800
        Component.onCompleted: {
            requestActivate(); //THIS SOLVED THE PROBLEM
            push(mainarea);
        }
    //Other elements here
}

推荐阅读