I have created Qt Quick 2Extension Plugin in the name of MyTestPlugin , inside I have created c++ file in the name of MySingleton, added QML_SINGLETON with in MySingleton class.
MySingleton.hpp
#ifndef TESTSINGLETON_H
#define TESTSINGLETON_H
#include <QQuickItem>
class TestSingleton : public QQuickItem
{
Q_OBJECT
Q_DISABLE_COPY(TestSingleton)
QML_SINGLETON
public:
explicit TestSingleton(QQuickItem *parent = nullptr);
~TestSingleton() override;
signals:
void testSignal();
public:
Q_INVOKABLE int testMethod();
};
#endif // MUSEAGORA_H
Then added codes below in MyTestPlugin.cpp
void MyTestPlugin::registerTypes(const char *uri)
{
// @uri TestSingleton
qmlRegisterSingletonInstance<TestSingleton>(uri, 1, 0, "TestSingleton", new TestSingleton());
}
Use qmlplugindump to create plugins.qmltypes:
import QtQuick.tooling 1.2
Module {
dependencies: [
"QtGraphicalEffects 1.12",
"QtQml 2.14",
"QtQml.Models 2.2",
"QtQuick 2.9",
"QtQuick.Controls 1.5",
"QtQuick.Controls.Styles 1.4",
"QtQuick.Extras 1.4",
"QtQuick.Layouts 1.1",
"QtQuick.Window 2.2"
]
Component {
name: "TestSingleton"
defaultProperty: "data"
prototype: "QQuickItem"
exports: ["MyTestPlugin/TestSingleton 1.0"]
isCreatable: false
isSingleton: true
exportMetaObjectRevisions: [0]
Signal { name: "testSignal" }
Method { name: "testMethod"; type: "int" }
}
}
Create a new project in qml import MyTestPlugin 1.0 and call MyTestPlugin.testMethod() output Aas below
<Unknown File>: Registered object must live in the same thread as the engine it was registered with
<Unknown File>: qmlRegisterSingletonType(): "TestSingleton" is not available because the callback function returns a null pointer.
qrc:/main.qml:285: TypeError: Property 'testMethod' of object [object Object] is not a function
Can plugin use C++ singleton? how should i use correctly?