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}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章