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

参考书籍《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}

猜你喜欢

转载自blog.csdn.net/weixin_43387612/article/details/105471324
今日推荐