QML自定义带参数信号槽

在组件之间通信,在QML中使用信号槽,并且有时需要携带参数,比如下面组件:

less 复制代码
Rectangle {
    id: root
    implicitWidth: 849
    implicitHeight: 480
    color: "#ffffff"
    radius: 15
    property string title1 : qsTr("Aux Temp Zone 1")
    property string title2 : qsTr("Aux 1 Name")
    property string auxTempZoneSwitchStatus   //辅助温区Switch状态,0表示关闭,1表示开启
    signal auxTempZoneSwitchChangeSignal(string checked)    //辅助温区Switch状态变化,0表示关闭,1表示开启

在这里定义一个信号,使用signal关键字,注意这里可以使用string类型,然后在发射信号的地方直接调用即可:

scss 复制代码
onCheckedChanged: {
                    auxTempZoneSwitchChangeSignal(getSwitchStringStatus(checked))
                }

接着就可以定义处理该信号的槽函数了:

less 复制代码
AuxTempItem{
                id: item1
                width: 849
                height: 477
                anchors.top: parent.top
                anchors.horizontalCenterOffset: 1
                anchors.topMargin: 52
                anchors.horizontalCenter: parent.horizontalCenter
                auxTempZoneSwitchStatus: GCDataPool.auxiliaryHeator1_config
                Connections{
                    target: item1
                    function onAuxTempZoneSwitchChangeSignal(value) {
                        console.log("onAuxTempZoneSwitchChangeSignal AuxTempItem", value)
                        GCDataPool.auxiliaryHeator1_config = value;
                    }
                }
            }

这里使用Connections关键字,第一个参数是target指明信号发出的对象,第二个参数必须是以function开头,on+信号名+(参数) 的形式,这个形式有2点需要注意:

  • 必须是on开头,加上信号的名字,以大写开始。
  • 参数不必声明类型,比如这里的(value),比如写成(string value)

如果我们还是以lambda的方式,比如下面这种:

ini 复制代码
Connections{
                    target: item1
                    onAuxTempZoneSwitchChangeSignal: {
                        console.log("AuxTempItem", value)
                        GCDataPool.auxiliaryHeator1_config = value;
                    }
                }

就会报错:# QML Connections: Implicitly defined onFoo properties in Connections are deprecated.

相关推荐
小小码农Come on9 小时前
Qt::WA_StyledBackground属性的作用
开发语言·qt
秋田君9 小时前
2026 前端新出路:掌握 C++ 核心语法,无缝衔接 QT 桌面开发
前端·c++·qt
走好每一步10 小时前
0、VDK编译 CMake + VS2017 x64
qt·vtk·三维图像
雪的季节12 小时前
Qt多窗口架构设计需求简介
开发语言·qt
jingshaoqi_ccc21 小时前
windows 10系统下QT的安装及在Visual studio中的扩展安装
windows·qt·visual studio
Starry-sky(jing)1 天前
# Linux 下 Qt 应用无障碍自动化:记一次wx无人值守系统的架构演进
linux·qt·自动化
必须得开心呀1 天前
QT 5.11.1使用QMetaObject::invokeMethod调用函数失败,提示提示 “no such method ***”
qt
誰能久伴不乏1 天前
工业级 Modbus 上位机架构:基于滴答引擎与状态锁的高并发调度器
c++·qt·架构
代钦塔拉1 天前
Qt信号槽参数类型全解:原生类型、结构体、enum class强枚举注册与传参实战
开发语言·qt
数据法师1 天前
Crow Translate :开源桌面划词翻译工具
c++·qt·开源