C++ Qt Quick2为Singleton类类型创建qmlRegisterSingletonType

C++ Qt Quick2为Singleton类类型创建qmlRegisterSingletonType,c++,qt,qml,singleton,qtquick2,C++,Qt,Qml,Singleton,Qtquick2,我试图使用qmlRegisterSingletonType创建singleton属性,但当我尝试访问QML中的对象时,控制台日志中出现以下错误: qrc:/qml/MyQml.qml:21 Element is not creatable. 下面是我的代码: //TestSingletonType.h类 #include <QObject> #include <QJsonObject> #include <QVariantMap> #include <

我试图使用
qmlRegisterSingletonType
创建singleton属性,但当我尝试访问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
};

#包括
#包括
#包括
#包括
类TestSingletonType:公共QObject
{
Q_对象
Q_禁用_复制(TestSingletonType)
TestSingletonType(QObject*parent=nullptr){}
公众:
//维护类的单个对象
静态QObject*qmlInstance(QQmlEngine*engine、QJSEngine*scriptEngine)
{
Q_未使用(发动机);
Q_未使用(脚本引擎);
if(instance==NULL)
instance=newtestsingletontype();
返回指令;
}
私人:
静态QObject*theInstance;//我已在Cpp文件中将其设置为NULL
};
//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();
} 
intmain(intargc,char*argv[])
{
QCoreApplication::setAttribute(Qt::AA_enableHighdDiscaling);
QGUI应用程序应用程序(argc、argv);
qqmlaplicationengine;
qmlRegisterSingletonType(“com.my.TestSingletonType”、1、0、“TestSingletonType”、&TestSingletonType::qmlInstance);
//用于加载QML的其余代码
返回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"
}
导入QtQuick 2.0
导入QtQuick.Controls 2.0
导入com.my.TestSingletonType 1.0
项目{

TestSingletonType{错误很明显:没有在QML中创建singleton,因为它已经在回调(QMLinInstance方法)中创建,您只需要访问该方法的属性。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
}