QML 鼠标和键盘事件

学习目标:Qml 鼠标和键盘事件

学习内容

1、QML 鼠标事件处理QML 直接提供 MouseArea 来捕获鼠标事件,该操作必须配合Rectangle 获取指定区域内的鼠标事件,

2、QML 键盘事件处理,并且获取对OML直接通过键盘事件 Keys 监控键盘任意按键应的消息。

项目效果

键盘事件

鼠标事件

项目代码

键盘事件

javascript 复制代码
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Rectangle{
        id:keyserctn
        anchors.centerIn: parent

        width: 450
        height: 200
        color: "green"

        // 不设置焦点,获取不了键盘事件
        focus: true

        //捕获键盘按键事件。
        Keys.onPressed: {
            //按下的按键的键值 相当于枚举的值 d:68
            console.log("key:"+event.key)
            //按下的按键的原生扫描码。 "A" 时,event.nativeScanCode 的值通常是 30。
            console.log("scancode:"+event.nativeScanCode)
            //按下的按键所对应的文本字符
            console.log("text:"+event.text)
        }
        //捕获特殊 tab键
        Keys.onTabPressed: {
            console.log("监控区域提示:你已经按下Tab键!")
        }
        //捕获特殊 空格键
        Keys.onSpacePressed: {
            console.log("监控区域提示:你已经按下空格键!")
        }
    }
}

鼠标事件

javascript 复制代码
import QtQuick 2.12
import QtQuick.Window 2.12

import QtQuick.Controls 2.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Rectangle{
        id :mouse
        anchors.centerIn: parent

        width: 450
        height: 200
        color: "red"

        radius: width/2

        //鼠标事件
        MouseArea{
            anchors.fill: parent //沾满
            //接受的按钮:全部
            acceptedButtons: Qt.AllButtons

            // 此属性为false,鼠标进入、离开、移动不能捕获到
            hoverEnabled: true

            onPositionChanged: {
                console.log("监控区域提示:你当前鼠标移动坐标为:("+mouseX+","+mouseY+")");
            }

            onClicked: {
                if(mouse.button===Qt.LeftButton){
                    console.log("监控区域提示:你已经按下鼠标左键!");
                }
                else if(mouse.button===Qt.RightButton){
                    console.log("监控区域提示:你已经按下鼠标右键!");
                }
                else if(mouse.button===Qt.MidButton){
                    console.log("监控区域提示:你已经按下鼠标中间键!");
                }
            }
            onDoubleClicked: {
                 console.log("监控区域提示:你已经双击按下鼠标!");
            }
        }

    }

}
最后附上源代码链接

对您有帮助的话,帮忙点个star

Qt demo: 学习qt过程 (gitee.com)

相关推荐
徐徐图之!11 小时前
你对键盘知多少?
计算机外设
ACP广源盛139246256731 天前
GSV6155@ACP#6155产品规格详解及产品应用分享
嵌入式硬件·计算机外设·音视频
电脑小管家2 天前
路由器怎么重新设置wifi密码
网络·windows·计算机外设·智能路由器·电脑
非凡ghost2 天前
Brightness.Manager.OK(显示器亮度调节软件)
android·智能手机·计算机外设·软件需求
hashiqimiya2 天前
拓展显示器,与显示器相关软件
计算机外设
uuleaf3 天前
26键打字训练小游戏:键盘练习游戏合集
游戏·计算机外设·编程打字
我送炭你添花3 天前
Pelco KBD300A 模拟器:01.Pelco 协议前世今生 & KBD300A 键盘基础解析
网络·python·计算机外设·pyqt
ezeroyoung4 天前
Flutter HarmonyOS 键盘高度监听插件开发指南
flutter·计算机外设·harmonyos
Ankie Wan5 天前
windows技巧:通过cmd禁止鼠标,键盘灯唤醒电脑。
windows·计算机外设·电脑
Chennnng5 天前
键盘参数选购
前端·css·计算机外设