QT键盘操作



  • 官方例子:
    1:
    The MyWidget code:
    Rectangle {
    id: widget
    color: "lightsteelblue"; width: 175; height: 25; radius: 10; antialiasing: true
    Text { id: label; anchors.centerIn: parent}
    focus: true
    Keys.onPressed: {
    if (event.key == Qt.Key_A)
    label.text = 'Key A was pressed'
    else if (event.key == Qt.Key_B)
    label.text = 'Key B was pressed'
    else if (event.key == Qt.Key_C)
    label.text = 'Key C was pressed'
    }
    }

    2:

    Rectangle {
    id: window
    color: "white"; width: 240; height: 150

    Column {
        anchors.centerIn: parent; spacing: 15
    
        MyWidget {
            focus: true             //set this MyWidget to receive the focus
            color: "lightblue"
        }
        MyWidget {
            color: "palegreen"
        }
    }
    

    }
    官方的结果是下面
    替代文字

    实际执行却是相反的。不管那个MyWidget焦点被设置true 结果都是 第一个被选中。不过这个本来就是一个用来显示焦点跑飞的例子。。 不用深究·加入FocusScope 的例子就可以了



  • @ppa2001 你需要这么写:

    // MyWidget.qml
    import QtQuick 2.0
    
    Rectangle {
        id: widget
        color: "lightsteelblue"; width: 175; height: 25; radius: 10; antialiasing: true
        Text { id: label; anchors.centerIn: parent}
        //focus: true// ×××××××××××××××××××××××注意这一行
        Keys.onPressed: {
            if (event.key == Qt.Key_A)
                label.text = 'Key A was pressed'
            else if (event.key == Qt.Key_B)
                label.text = 'Key B was pressed'
            else if (event.key == Qt.Key_C)
                label.text = 'Key C was pressed'
        }
    }
    
    
    // main.qml
    import QtQuick 2.5
    import QtQuick.Window 2.2
    
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
    
        Rectangle {
            id: window
            color: "white"; width: 240; height: 150
    
            Column {
                anchors.centerIn: parent; spacing: 15
    
                MyWidget {
                    color: "lightblue"
                }
                MyWidget {
                    focus: true             //set this MyWidget to receive the focus
                    color: "palegreen"
                }
            }
        }
    }
    

    这么写的话即可达到效果哦。


登录后回复
 

与 萌梦社区 的连接断开,我们正在尝试重连,请耐心等待