Qt 小例子学习39 - 获取qmldir中Singleton 对象的实例

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();
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值