首页 > 解决方案 > 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

标签: c++qtqml

解决方案


我找到了解决方案。在 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 中通知


推荐阅读