#qt #qml
#qt #qml
Вопрос:
Я создал Qt Quick 2Extension плагин с именем MyTestPlugin , внутри я создал файл c с именем MySingleton, добавил QML_SINGLETON с помощью класса MySingleton.
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
Затем добавлены коды ниже в MyTestPlugin.cpp
void MyTestPlugin::registerTypes(const char *uri)
{
// @uri TestSingleton
qmlRegisterSingletonInstance<TestSingleton>(uri, 1, 0, "TestSingleton", new TestSingleton());
}
Используйте qmlplugindump для создания плагинов.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" }
}
}
Создайте новый проект в qml, импортируйте MyTestPlugin 1.0 и вызовите MyTestPlugin.TestMethod()
выведите Aas ниже
<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
Может ли плагин использовать C singleton?
как я должен правильно использовать?
Ответ №1:
Я сам нашел способ
static QObject *test_singleton_type_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
TestSingleton *e = new TestSingleton();
return e;
}
void MuseAgoraPlugin::registerTypes(const char *uri)
{
// @uri TestSingleton
qmlRegisterSingletonType< TestSingleton >(uri, 1, 0, "TestSingleton", test_singleton_type_provider);
}