• QT QML Keys 处理注意事项


    今天在学习 QT QML 最基本的东东,在下面的代码中响应按键处理无效。代码如下:

     1 import QtQuick 2.2
     2 import QtQuick.Window 2.1
     3 import QtQuick.Controls 1.2
     4 
     5 Window {
     6     visible: true
     7      360
     8     height: 360
     9 
    10     MouseArea {
    11         anchors.fill: parent
    12         onClicked: {
    13             Qt.quit();
    14         }
    15     }
    16 
    17     Text {
    18         id: helloWorldTxt;
    19         text: qsTr("Hello World")
    20         anchors.centerIn: parent
    21     }
    22 
    23     Button {
    24         id: quitBtn;
    25         text: "Quit";
    26         anchors.horizontalCenter: helloWorldTxt.horizontalCenter;
    27         anchors.top: helloWorldTxt.bottom;
    28         anchors.bottomMargin: 8;
    29         onClicked: {
    30             console.log("click quit button.");
    31             Qt.quit();      // 如果没有此行,则点击此按键不会退出.
    32         }
    33     }
    34 
    35     // focus: true;            // 错误: Invalid property name
    36     Keys.enabled: true;
    37     Keys.onEscapePressed: {
    38         Qt.quit();  // 没有功能: 不退出, why?
    39     }
    40     Keys.onPressed: {
    41         switch(event.key) {
    42         case Qt.Key_0:
    43             console.log("click key 0.");        // 一样没有 LOG 输出
    44             break;
    45         default:
    46             console.log("click key other.");
    47             break;
    48         }
    49     }
    50 }

    将 Keys 的处理放在 Item 中、并且增加: focus: true; 后,功能正常。

    代码如下(省略部分重复的代码):

     1 import QtQuick 2.2
     2 import QtQuick.Window 2.1
     3 import QtQuick.Controls 1.2
     4 
     5 Window {
     6     ......
     7 
     8     Item {
     9         focus: true;            // 此句是必须的, 否则没有功能
    10         Keys.enabled: true;
    11         Keys.onEscapePressed: {
    12             Qt.quit();  // 功能正常
    13         }
    14         Keys.onPressed: {
    15             switch(event.key) {
    16             case Qt.Key_0:
    17                 console.log("click key 0.");        // 有 LOG 输出
    18                 break;
    19             default:
    20                 console.log("click key other.");
    21                 break;
    22             }
    23         }
    24     }
    25 }
  • 相关阅读:
    关于global和$GLOBALS[]的一些实践
    java环境配置的新手教程
    echart图表 resize()方法使用
    使用git上传下载项目
    windows 系统新建 vue 项目的坑
    Java版求1000以内的完全数
    Java版经典兔子繁殖迭代问题——斐波那契(Fibonacci)数列
    Java版冒泡排序和选择排序
    AngularJS 动画总结
    Mac下sublime text 的“package control”安装
  • 原文地址:https://www.cnblogs.com/91program/p/5952291.html
Copyright © 2020-2023  润新知