我有一个类可以在没有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发布于 2021-09-30 14:49:36
我找到了一个解决方案。在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中通知
https://stackoverflow.com/questions/69373967
复制相似问题