QML signal 使用简要记录

1.主动触发

import QtQuick 2.3

Rectangle {
    width: 200
    height: 100
    signal test  //定义信号

    Text {
        anchors.centerIn: parent
        text: "Hello, World!"
    }

    MouseArea{
	 anchors.fill: parent
	 onClicked:{
		test()
		value = 10;
	 }
    }
    onTest:{
	console.log("test")
    }
}

2.属性变更触发

import QtQuick 2.3

Rectangle {
    width: 200
    height: 100

    property int value;//定义属性

    Text {
        anchors.centerIn: parent
        text: "Hello, World!"
    }

   MouseArea{
   	 anchors.fill: parent
   	 onClicked:{
   		value++
   	 }
   }
   //属性值变更 主动触发
   onValueChanged:{
   	console.log(value)
   }
}

3.使用Connections连接

  import QtQuick 2.13
  import QtQuick.Controls 2.13

  Rectangle {
      id: rect
      width: 250; height: 250

      Button {
          id: button
          anchors.bottom: parent.bottom
          anchors.horizontalCenter: parent.horizontalCenter
          text: "Change color!"
      }

      Connections {
          target: button
          onClicked: {
              rect.color = Qt.rgba(Math.random(), Math.random(), Math.random(), 1);
          }
      }
  }

4.附加信号句柄

  import QtQuick 2.13

  Rectangle {
      width: 200; height: 200
      color: Qt.rgba(Qt.random(), Qt.random(), Qt.random(), 1)
      //当Rectangle创建完毕后 会触发
      //附加信号,使得对象可以不添加新的代码 接受到专属信号
      Component.onCompleted: {
          console.log("The rectangle's color is", color)
      }
  }

5.信号+信号|方法 连接

import QtQuick 2.3

Rectangle {
    width: 200
    height: 100
    signal test
    Text {
        anchors.centerIn: parent
        text: "Hello, World!"
    }

   MouseArea{
	 id: mouse
   	 anchors.fill: parent

   }
   onTest:{
   	console.log("test")
   }
   //定义方法
   function dosomething(){
	console.log("do something")
   }

   Component.onCompleted: {
	mouse.clicked.connect(test)	   //信号连接信号 disconnect 断开连接
	mouse.clicked.connect(dosomething) //信号连接方法
    }
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值