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.

相关推荐
weixin_4643076310 小时前
QT中加载PSQL驱动
qt
~光~~10 小时前
【环境配置 】WSL2 +ubuntu20.04 +Qt配置+Kits配置
开发语言·qt·ubuntu
老歌老听老掉牙15 小时前
基于 PyQt5 实现刀具类型选择界面的设计与交互逻辑
python·qt·交互
灵性花火21 小时前
Qt绘制折线图
qt
abcd_zjq1 天前
【2025最新】【win10】vs2026+qt6.9+opencv(cmake编译opencv_contrib拓展模
人工智能·qt·opencv·计算机视觉·visual studio
abcd_zjq1 天前
VS2026+QT6.9+opencv图像增强(多帧平均降噪)(CLAHE对比度增强)(边缘增强)(图像超分辨率)
c++·图像处理·qt·opencv·visual studio
Algebraaaaa1 天前
Qt中的字符串宏 | 编译期检查和运行期检查 | Qt信号与槽connect写法
开发语言·c++·qt
友友马1 天前
『 QT 』Hello World控件实现指南
开发语言·qt
誰能久伴不乏1 天前
如何在 Linux_Ubuntu 上安装 Qt 5:详细教程
linux·qt·ubuntu
feiyangqingyun1 天前
有难度哦/Qt基于通用地图组件实现航迹规划和模拟/动态标注轨迹线/带序号和方向箭头指示
qt·航迹规划和模拟