QML建立信号连接方式
学习QML自定义控件,并连接信号槽方式
本文主要学习QML信号槽建立连接的方式:
方式一:
Component.onCompleted: {
// 信号signal1
item1.signal1.connect(slot1);
}
// 槽函数
function slot1()
{
console.log(“slot1 in!”);
}
方式二:
Connections{
target: item1
// 信号signal1,on + 信号(首字母大写)
onSignal1: { // 槽函数
console.log(“slot1 in!”);
}
}
// 自定义封装按键控件
import QtQuick 2.0
import QtQuick.Controls 2.2
Rectangle {
id: buttonComponents
width: 60
height: 30
property string text: "pressed"
signal buttonSignal();
Button {
id: buttonID
width: buttonComponents.width
height: buttonComponents.height
text: buttonComponents.text
onClicked: {
console.log(text)
buttonComponents.buttonSignal()
}
}
}
// 主窗体
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Test")
color: "gray"
Row{
id : rowId
spacing: 5
padding: 5
ComButton{
id: button1
text: "button1"
}
ComButton{
id: button2
text: "button2"
}
ComButton{
id: button3
text: "button3"
}
}
// 连接信号槽方式一
Component.onCompleted: {
button1.buttonSignal.connect(onButton1Clicked);
}
// 连接信号槽方式二
Connections{
target: button1
onButtonSignal: {
console.log("receive Button1");
}
}
function onButton1Clicked()
{
console.log("onButton1Clicked in!");
}
}