QML手动连接信号槽【Connections】

时间:2022-12-23 19:41:20

1、使用Connections

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
visible: true
width:
height:
title: qsTr("Hello World") Text {
id: text1;
text: qsTr("text1");
anchors.top: parent.top;
anchors.topMargin: ;
anchors.horizontalCenter: parent.horizontalCenter;
anchors.centerIn: parent;
font.pixelSize: ;
color: "red";
}
Text {
id: text2;
text: qsTr("text2");
anchors.top: text1.bottom;
anchors.topMargin: ;
anchors.horizontalCenter: parent.horizontalCenter;
font.pixelSize: ;
}
Button{
id:btn;
text: "btn";
anchors.horizontalCenter: parent.horizontalCenter;
anchors.top:text2.bottom;
anchors.topMargin: ;
} Connections{
target: btn;
onClicked:{
text1.color
=Qt.rgba(Math.random(),Math.random(),Math.random(),);
text2.color=Qt.rgba(Math.random(),Math.random(),Math.random(),
);
}
}

}

QML手动连接信号槽【Connections】

上述代码等于【在btn的onClicked里直接加改变颜色的代码】

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
visible: true
width:
height:
title: qsTr("Hello World") Text {
id: text1;
text: qsTr("text1");
anchors.top: parent.top;
anchors.topMargin: ;
anchors.horizontalCenter: parent.horizontalCenter;
anchors.centerIn: parent;
font.pixelSize: ;
color: "red";
}
Text {
id: text2;
text: qsTr("text2");
anchors.top: text1.bottom;
anchors.topMargin: ;
anchors.horizontalCenter: parent.horizontalCenter;
font.pixelSize: ;
}
Button{
id:btn;
text: "btn";
anchors.horizontalCenter: parent.horizontalCenter;
anchors.top:text2.bottom;
anchors.topMargin: ;
onClicked: {
text1.color=Qt.rgba(Math.random(),Math.random(),Math.random(),);
text2.color=Qt.rgba(Math.random(),Math.random(),Math.random(),);
}
}
}

2、使用signal.connect

QML手动连接信号槽【Connections】