Qt Quick2为单例类类型创建qmlRegisterSingletonType

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

我正在尝试使用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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.