I have a class that can create dynamic properties without 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
Is it possible in the property QQmlPropertyMap have QQmlPropertyMap. To get a subproperty. Something like this in qml:
text: MyClass.Test2.SubTest1
CodePudding user response:
I found a solution. In myclass.h declare
Q_DECLARE_METATYPE(QQmlPropertyMap*)
In the constructor of 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");
});
Now in qml you can do this
text: MyClass.Test2.SubTest1
Thanks to this, you can create dynamic properties and sub-properties without Q_PROPERTY and change values from C , all changes will be notified in qml