M
M
Maxim Rudnev2017-06-21 12:27:46
Qt
Maxim Rudnev, 2017-06-21 12:27:46

How to pass this singleton C++ class to QML?

There is a c++ singleton class.
It is necessary to throw it into QML.
A normal, non-singleton class does not cause problems.
onlyone.h

#ifndef ONLYONE_H
#define ONLYONE_H
#include <QObject>

class OnlyOne : public QObject
{
    Q_OBJECT
public:
    static const OnlyOne& Instance()
    {
        static OnlyOne theSingleInstance;
        return theSingleInstance;
    }
private:
    OnlyOne() {}
    OnlyOne(const OnlyOne& root);
    OnlyOne& operator=(const OnlyOne&);
};

#endif // ONLYONE_H

main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <onlyone.h>
#include <QDesktopServices>
#include <QtWidgets/QWidget>
#include <QQmlEngine>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    
    auto& s=OnlyOne::Instance();
    qmlRegisterType<OnlyOne>("singleton", 1, 0, "MyTreeModel" );
    QQmlApplicationEngine engine;


    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;


    return app.exec();
}

compiler log:
667610ffaea44cc79db935749fd0648e.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TriKrista, 2017-06-21
@stigmt

doc.qt.io/qt-5/qqmlengine.html#qmlRegisterSingletonType

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question