QtQuick(QML)自学之路(4)信号与槽

参考书籍《Qt quick 核心编程》
书籍作者:https

信号处理器和附加信号处理器(前面有说)

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

使用signal.connect()

signal.connect允许连接一个信号到另一个信号或者方法,可以做到一个信号连接多个方法。

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");

    Rectangle {
    
    //矩形
        id:ret;
        anchors.centerIn: parent;
        color:"black";
        width: 200;
        height: 200;
    }
    Button {
    
    
        id:btn;
        text:"change";
        anchors.top:ret.bottom;
        anchors.horizontalCenter: ret.horizontalCenter;
        anchors.topMargin: 20;//顶部边缘距离 20

    }
    Component.onCompleted: {
    
    
        btn.clicked.connect(testConnect)
        btn.clicked.connect(change)
    }
    function testConnect(){
    
    
        ret.color = "blue";
    }
    function change() {
    
    
        ret.width-=10;
        ret.height-=10;
    }
}

Component.onCompleted这里我也不知道为什么要用这个,有待后续了解。
在这里插入图片描述

使用connections

通过on{Signal} 可以做到快速连接,但是当

  1. 你需要将多个对象连接到同一个 QML 信号上
  2. 你需要在发出信号的对象的作用域之外来建立连接
  3. 发射信号的对象没有在 QML 中定义(可能是通过 C++ 导出的)
Connections {
    
    
	//连接的对象 如Button
    target: area;
    //对象的信号处理器,如onClicked
    on{
    
    Signal}: function or code block;
}

随便写个运行下,实在想不到什么场景用到

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");

    Rectangle {
    
    //矩形
        id:ret;
        anchors.centerIn: parent;
        color:"black";
        width: 200;
        height: 200;
    }
    Button {
    
    
        id:btn;
        text:"change";
        anchors.top:ret.bottom;
        anchors.horizontalCenter: ret.horizontalCenter;
        anchors.topMargin: 20;//顶部边缘距离 20
    }
    Connections {
    
    
        target: btn;// Button的id
        onClicked: {
    
    
            ret.width-=10;
            ret.height-=10;
            ret.color = "blue";
        }
    }
}

上面的例子做到的效果都是一样的,所以这里就不放图了。

猜你喜欢

转载自blog.csdn.net/weixin_43387612/article/details/105472611