c++ - QQmlPropertyMap 在属性 QQmlPropertyMap
问题描述
我有一个可以在没有 Q_PROPERTY 的情况下创建动态属性的类
//myclass.h
#include <QQmlEngine>
#include <QQmlPropertyMap>
class MyClass : public QQmlPropertyMap
{
public:
static MyClass& instance();
~MyClass() override = default;
Q_DISABLE_COPY_MOVE(MyClass)
private:
explicit MyClass();
};
QObject *qmlMyClassInterface(QQmlEngine *engine, QJSEngine *scriptEngine);
//myclass.cpp
#include "myclass.h"
#include <QTimer>
QObject *qmlMyClassInterface(QQmlEngine *engine, QJSEngine *scriptEngine) {
Q_UNUSED(scriptEngine)
MyClass *p = &MyClass::instance();
engine->setObjectOwnership(p, QQmlEngine::CppOwnership);
return p;
}
MyClass &MyClass::instance() {
static MyClass singleton;
return singleton;
}
MyClass::MyClass() {
insert("Test1", "Test 1");
insert("Test2", "Test 2");
QTimer::singleShot(3000, [this]{
insert("Test1", "Update test 1");
insert("Test2", "Update test 2");});
}
//main.cpp
#include "myclass.h"
qmlRegisterSingletonType<MyClass>("MyClass", 1, 0, "MyClass", qmlMyClassInterface);
//main.qml
import MyClass 1.0
title: MyClass.Test1
text: MyClass.Test2
QQmlPropertyMap中是否有可能有QQmlPropertyMap。获取子属性。在 qml 中是这样的:
text: MyClass.Test2.SubTest1
解决方案
我找到了解决方案。在 myclass.h 中声明
Q_DECLARE_METATYPE(QQmlPropertyMap*)
在 MyClass 的构造函数中
QQmlPropertyMap *subProperty = new QQmlPropertyMap(this);
subProperty->insert("SubTest1", "some text");
QVariant stored;
stored.setValue(subProperty);
insert("Test2", stored);
QTimer::singleShot(3000, [subProperty]{
subProperty->insert("SubTest1", "Update some text");
});
现在在 qml 你可以做到这一点
text: MyClass.Test2.SubTest1
多亏了这一点,您可以在没有 Q_PROPERTY 的情况下创建动态属性和子属性并从 C++ 更改值,所有更改都将在 qml 中通知
推荐阅读
- cakephp-3.0 - cakephp 如何使用一个日期和时间间隔创建和保存表单
- azure-devops - ADO:如果从发布触发的构建失败,如何标记发布定义失败
- php - 验证逻辑,在特定给定日期执行特定操作
- sql - 在 ORACLE SQL 中,比较 2 个字符串时出现问题('E' > 'e' 表示为真)
- html - HTML 输入元素重置为默认值
- python - 使用 POST 请求对 Unity Analytics 进行身份验证
- cassandra - cassandra - 端口 7000 没有在监听 - 如何让它“监听”?
- reactjs - 在d3弧内的路径/文本上添加文本,textPath不显示?
- javascript - 我在运行后遇到 TypeScript 反应错误,而在其他设备上它可以,仅在我的 Mac 上
- python - 如何在 python 中使用 PIL 读取图像的 HSV 值?