Qt Quick2 为Singleton类类型创建qmlRegisterSingletonType。

问题描述 投票:0回答:1

我正试图通过使用 qmlRegisterSingletonType 但当我试图访问QML中的对象时,我在控制台日志中得到以下错误。

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

以下是我的代码。

/ TestSingletonType.h Class

#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.

我参考了下面的答案和链接。如何为qmlRegisterSingletonType实现一个单人提供者? https:/doc.qt.ioqt-5qqmlengine.html#qmlRegisterSingletonType。

c++ qt singleton qtquick2 qt-quick
1个回答
1
投票

这个错误很明显:在QML中并没有创建一个单体,因为它已经在回调中创建了(qmlInstance方法),你只需要访问该方法的属性。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
}
© www.soinside.com 2019 - 2024. All rights reserved.