QtQuick(QML)自学之路(3)信号处理器

9 篇文章 0 订阅

参考书籍《Qt quick 核心编程》
书籍作者:https://blog.csdn.net/foruok/article/details/30028711

一个简单的例子(使用已知信号)

import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.14  //使用Button
Window {
    id:root;
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World");

    Text {
        id: txt;
        text: qsTr("text");
        font.pointSize: 24;
        anchors.centerIn: parent;
    }

    Button {
        id:btn;
        text: "change";
        anchors.top: txt.bottom;//锚在txt的下方
        anchors.horizontalCenter: txt.horizontalCenter;//对齐txt的中心
        onClicked: {//信号处理器,信号为clicked
            txt.text = "CHANGE";//更改txt的文本
        }
    }
}

从官方文档可以看到Button有clicked的信号,而我们在使用的时候需要特定的格式on{Signal},以 on 起始后跟信号名字,如clicked对应onClicked。
在这里插入图片描述

附加信号处理器

先看一个错误例子

import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.14
Window {
    id:root;
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World");

    Text {
        id: txt;
        text: qsTr("text");
        font.pointSize: 24;
        x:0;
        y:0;
    }
    Keys.enabled: true;
    Keys.onRightPressed: {
        txt.x = txt.x+10;
    }
    Keys.onLeftPressed: {
        txt.x = txt.x-10;
    }
    Keys.onUpPressed: {
        txt.x = txt.y-10;
    }
    Keys.onDownPressed: {
        txt.x = txt.y+10;
    }
}

想当然的写结果报了错,

D:\LEARN\THE_QML\2020_04_09_test\test>qmlscene main.qml
Could not attach Keys property to: QQuickWindowQmlImpl(0x352b3e8) is not an Item

这个是正确的例子,运行后可以通过按键控制文本移动,注意 ,要把Keys放在Text内部,并且要开启焦点。

import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.14
Window {
    id:root;
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World");

    Text {
        id: txt;
        text: qsTr("text");
        font.pointSize: 24;

        Keys.onRightPressed: x+=10;
        Keys.onLeftPressed: {
            x-=10;
        }
        Keys.onUpPressed: {
            y-=10;
        }
        Keys.onDownPressed: {
            y+=10;
        }
        focus:true;//焦点,不然无法处理按键
    }
}

其中的 Keys.onDownPressed之类便是附加信号处理器,格式为{Attaching Type}.on{Signal}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值