gpt4 book ai didi

c++ - Qt Quick2为单例类类型创建qmlRegisterSingletonType

转载 作者:行者123 更新时间:2023-12-01 14:52:37 26 4
gpt4 key购买 nike

我试图使用qmlRegisterSingletonType创建单例属性,但是当我尝试访问QML中的对象时,控制台日志中出现以下错误:

qrc:/qml/MyQml.qml:21 Element is not creatable.

下面是我的代码:

// TestSingletonType.h类
#include <QObject>
#include <QJsonObject>
#include <QVariantMap>
#include <QQmlEngine>

class TestSingletonType : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(TestSingletonType)
TestSingletonType(QObject *parent = nullptr) {}

public:

// To maintain single object of the class
static QObject *qmlInstance(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine);
Q_UNUSED(scriptEngine);

if (theInstance == NULL)
theInstance = new TestSingletonType();

return theInstance;
}

private:

static QObject *theInstance; // I have set it to NULL in Cpp file
};


// Main.cpp
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;

qmlRegisterSingletonType<TestSingletonType>("com.my.TestSingletonType", 1, 0, "TestSingletonType", &TestSingletonType::qmlInstance);

// Rest of the code to load the QML

return app.exec();
}

// MyQml.qml文件:
import QtQuick 2.0
import QtQuick.Controls 2.0
import com.my.TestSingletonType 1.0

Item {

TestSingletonType { <---- Getting error on this line
id: mySingleClass
}

// Rest of my code which uses "mySingleClass"
}

如果我使用 qmlRegisterType,那么它可以正常工作,但不能与 qmlRegisterSingletonType一起工作。

我已提及以下答案和链接:
How to implement a singleton provider for qmlRegisterSingletonType?
https://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterSingletonType

最佳答案

错误很明显:由于在回调(qmlInstance方法)中已经创建了一个单例,因此不会在QML中创建它,您只需要访问该方法的属性即可。 typeName(“TestSingletonType”)是ID。

Item {
// binding property
foo_property : TestSingletonType.foo_value
// update singleton property
onAnotherPropertyChanged: TestSingletonType.another_prop = anotherProperty
}

// listen singleton signal
Connections{
target: TestSingletonType
onBarChanged: bar_object.bar_property = bar
}

关于c++ - Qt Quick2为单例类类型创建qmlRegisterSingletonType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62104907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com