Qt 小例子学习39 - 获取qmldir中Singleton 对象的实例
SingletonBaseClass.h
#ifndef SINGLETONBASECLASS_H
#define SINGLETONBASECLASS_H
#include <QObject>
#include <QQmlComponent>
#include <QQmlContext>
#include <QQmlEngine>
#include <QDebug>
class SingletonBaseClass : public QObject
{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
public:
explicit SingletonBaseClass(QObject *parent = nullptr) : QObject(parent) {}
QString text() const { return mText; }
void setText(const QString &text)
{
if (mText == text)
return;
mText = text;
emit textChanged();
}
Q_INVOKABLE void someMethodCalledFromQml()
{
QQmlEngine *ownerEngine = QQmlEngine::contextForObject(this)->engine();
qDebug() << ownerEngine;
}
static SingletonBaseClass *instance(QQmlEngine *engine)
{
QQmlComponent component(engine, QUrl("qrc:/tmp.qml"));
QObject *item = component.create();
SingletonBaseClass *instance =
qvariant_cast<SingletonBaseClass *>(item->property("obj"));
return instance;
}
signals:
void textChanged();
private:
QString mText;
};
#endif // SINGLETONBASECLASS_H
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
visible: true
width: 640
height: 480
title: SingletonClass.text
Button {
text: "Button"
onClicked: SingletonClass.someMethodCalledFromQml()
}
}
SingletonClass.qml
import QtQml 2.0
import SingletonBaseClass 1.0
pragma Singleton
SingletonBaseClass {
text: "hola"
}
tmp.qml
import QtQuick 2.0
QtObject {
property var obj: SingletonClass
}
qmldir
module Component
singleton SingletonClass 1.0 SingletonClass.qml
main.cpp
#include "singletonbaseclass.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QDebug>
int main(int argc, char *argv[])
{
#if defined(Q_OS_WIN)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<SingletonBaseClass>("SingletonBaseClass", 1, 0,
"SingletonBaseClass");
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
qDebug() << SingletonBaseClass::instance(&engine);
return app.exec();
}