目录
- 使用场景
- 传统方式
- 高效方式
- 代码
- 效果展示
使用场景
界面嵌套关系如下
传统方式
单纯用qml来传递多层信号,只能在每一层添加signal, 逐层触发,非常麻烦
我尝试过Connections, target使用: Panel2. Panel3. Panel4, 但是不生效
高效方式
使用C++类作为信号中转
代码
qml界面
// RootPanel
import QtQuick 2.15
import QtQuick.Layouts 1.2
ColumnLayout {
spacing: 20
Panel01 {
Layout.preferredWidth: 200
Layout.preferredHeight: 50
}
Panel02 {
Layout.preferredWidth: 200
Layout.preferredHeight: 50
}
}
// Panel02
import QtQuick 2.15
Item {
// Detected anchors on an item that is managed by a layout
// anchors.fill: parent
Panel03 { anchors.fill: parent }
}
// Panel03
import QtQuick 2.15
Item {
anchors.fill: parent
Panel04{
anchors.fill: parent
}
}
// Panel04
import QtQuick 2.15
import QtQuick.Controls 2.15
Button {
property int index: 0
anchors.fill: parent
text: "panel 4: " + index
font.pixelSize: 20
onClicked: {
index ++
// 触发C++中的信号
toolWorker.sigAddIndex(index)
}
background: Rectangle{
color: "lightGreen"
}
}
// Panel01
import QtQuick 2.15
import QtQuick.Controls 2.15
Button {
property int index: 0
text: "panel 1: " + index
font.pixelSize: 20
// 这里只是简单的属性传递,其实可以使用属性绑定
// Connections最适合复杂逻辑场景
Connections {
target: toolWorker
function onSigAddIndex(val) {
index = val
console.log("index", index)
}
}
}
C++
这里使用单例模式
// ToolWorker.h
#ifndef TOOLWORKER_H
#define TOOLWORKER_H
#include <QObject>
class ToolWorker : public QObject
{
Q_OBJECT
public:
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());