QML手動連接信號槽【Connections】


1、使用Connections

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Text {
        id: text1;
        text: qsTr("text1");
        anchors.top: parent.top;
        anchors.topMargin: 10;
        anchors.horizontalCenter: parent.horizontalCenter;
        anchors.centerIn: parent;
        font.pixelSize: 20;
        color: "red";
    }
    Text {
        id: text2;
        text: qsTr("text2");
        anchors.top: text1.bottom;
        anchors.topMargin: 10;
        anchors.horizontalCenter: parent.horizontalCenter;
        font.pixelSize: 20;
    }
    Button{
        id:btn;
        text: "btn";
        anchors.horizontalCenter: parent.horizontalCenter;
        anchors.top:text2.bottom;
        anchors.topMargin: 10;
    }

 Connections{ target: btn; onClicked:{ text1.color=Qt.rgba(Math.random(),Math.random(),Math.random(),1); text2.color=Qt.rgba(Math.random(),Math.random(),Math.random(),1); } }
}

 上述代碼等於【在btn的onClicked里直接加改變顏色的代碼】

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Text {
        id: text1;
        text: qsTr("text1");
        anchors.top: parent.top;
        anchors.topMargin: 10;
        anchors.horizontalCenter: parent.horizontalCenter;
        anchors.centerIn: parent;
        font.pixelSize: 20;
        color: "red";
    }
    Text {
        id: text2;
        text: qsTr("text2");
        anchors.top: text1.bottom;
        anchors.topMargin: 10;
        anchors.horizontalCenter: parent.horizontalCenter;
        font.pixelSize: 20;
    }
    Button{
        id:btn;
        text: "btn";
        anchors.horizontalCenter: parent.horizontalCenter;
        anchors.top:text2.bottom;
        anchors.topMargin: 10;
        onClicked: {
            text1.color=Qt.rgba(Math.random(),Math.random(),Math.random(),1);
            text2.color=Qt.rgba(Math.random(),Math.random(),Math.random(),1);
        }
    }
}

 2、使用signal.connect

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM