QML(26)——多层qml界面传递信号
目录
- 使用场景
- 传统方式
- 高效方式
- 代码
- 效果展示
使用场景
界面嵌套关系如下
传统方式
单纯用qml来传递多层信号,只能在每一层添加signal, 逐层触发,非常麻烦
我尝试过Connections, target使用: Panel2. Panel3. Panel4, 但是不生效
高效方式
使用C++类作为信号中转
代码
qml界面
// RootPanel
import QtQuick 2.15
import QtQuick.Layouts 1.2ColumnLayout {spacing: 20Panel01 {Layout.preferredWidth: 200Layout.preferredHeight: 50}Panel02 {Layout.preferredWidth: 200Layout.preferredHeight: 50}
}// Panel02
import QtQuick 2.15
Item {
// Detected anchors on an item that is managed by a layout
// anchors.fill: parentPanel03 { anchors.fill: parent }
}// Panel03
import QtQuick 2.15Item {anchors.fill: parentPanel04{anchors.fill: parent}
}// Panel04
import QtQuick 2.15
import QtQuick.Controls 2.15Button {property int index: 0anchors.fill: parenttext: "panel 4: " + indexfont.pixelSize: 20onClicked: {index ++// 触发C++中的信号toolWorker.sigAddIndex(index)}background: Rectangle{color: "lightGreen"}
}// Panel01
import QtQuick 2.15
import QtQuick.Controls 2.15Button {property int index: 0text: "panel 1: " + indexfont.pixelSize: 20// 这里只是简单的属性传递,其实可以使用属性绑定// Connections最适合复杂逻辑场景Connections {target: toolWorkerfunction onSigAddIndex(val) {index = valconsole.log("index", index)}}
}
C++
这里使用单例模式
// ToolWorker.h
#ifndef TOOLWORKER_H
#define TOOLWORKER_H#include <QObject>class ToolWorker : public QObject
{Q_OBJECTpublic:static ToolWorker &GetInstance();private:ToolWorker();~ToolWorker();ToolWorker(const ToolWorker &) = delete;ToolWorker(const ToolWorker &&) = delete;ToolWorker &operator=(const ToolWorker &) = delete;signals:void sigAddIndex(int val);public slots:
};
#endif // TOOLWORKER_H// ToolWorker.cpp
#include "ToolWorker.h"
ToolWorker &ToolWorker::GetInstance()
{static ToolWorker myTool;return myTool;
}
ToolWorker::ToolWorker(){}
ToolWorker::~ToolWorker(){}
main.cpp
添加以下内容
#include <QQmlContext>
#include "ToolWorker.h"engine.rootContext()->setContextProperty("toolWorker", &ToolWorker::GetInstance());
发布评论