首页 > 技术文章 > 《Qt Quick 4小时入门》学习笔记4

sdsunjing 2016-09-24 17:14 原文

http://edu.csdn.net/course/detail/1042/14806?auto_start=1

Qt Quick 4小时入门
第七章:处理鼠标与键盘事件

1、处理鼠标事件
鼠标信号传递一个MouseEvent类型的mouse参数

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import QtQuick.Window 2.0

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

    // 处理鼠标事件示例
    MouseArea {
        anchors.fill: parent; // 在哪个区域之内接收鼠标事件
        acceptedButtons: Qt.LeftButton | Qt.RightButton; // 鼠标的左键和右键事件
        onClicked: {
            if (mouse.button == Qt.LeftButton) {
                txt.text = "您点击了左键。";
            } else if (mouse.button == Qt.RightButton) {
                txt.text = "您点击了右键。";
            }
        }

        onDoubleClicked: {
            if (mouse.button == Qt.LeftButton) {
                txt.text = "您双击了左键。";
            } else if (mouse.button == Qt.RightButton) {
                txt.text = "您双击了右键。";
            }
        }
    }
}

2、处理键盘事件

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import QtQuick.Window 2.0

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

    // 处理键盘事件示例
    Text {
        id: txt;
        text: "齐天大圣";
        width: 60*8;
        font.pointSize: 50;
        x: 100;
        y: 200;
        //anchors.centerIn: parent; // 如果执行下面的代码改变文本的位置,那么不能使用锚布局
        // Window对象不能处理按键事件,需要放到一个Item对象里
        Keys.onLeftPressed: x -= 10;
        Keys.onRightPressed: x += 10;
        Keys.onUpPressed: y -= 10;
        Keys.onDownPressed: y += 10;
        focus: true; // 只有拥有焦点的Item才能处理按键事件
    }
}

Keys是一个附加属性
QML中的属性就是C++中的成员变量。

属性的类型:
(1)基本类型
(2)id属性:可以在其他对象或脚本中通过id引用本对象
(3)列表属性
(4)信号处理器
(5)分组属性:
Text {
    font { pixelSize: 12; bold: true; }
}
(6)附加属性


来自为知笔记(Wiz)


推荐阅读