aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/doc/snippets/qml/exposing-state/singleton.h
blob: e600531883a2b1fcdcd0962bbae02d15765d3f2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#ifndef SINGLETON_H
#define SINGLETON_H

#include <QtQml/qobject.h>
#include <QtQml/qqml.h>
#include <QtQml/qqmlengine.h>

//![0]
// Singleton.h
class Singleton : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int thing READ thing WRITE setThing NOTIFY thingChanged FINAL)
    QML_ELEMENT
    QML_SINGLETON

public:
    Singleton(QObject *parent = nullptr) : QObject(parent) {}

    int thing() const { return m_value; }
    void setThing(int v)
    {
        if (v != m_value) {
            m_value = v;
            emit thingChanged();
        }
    }

signals:
    void thingChanged();

private:
    int m_value = 12;
};
//![0]

inline void setTheThing(QQmlEngine *engine)
{
//![1]
    Singleton *singleton
            = engine->singletonInstance<Singleton *>("MyModule", "Singleton");
    singleton->setThing(77);
//![1]
}

#endif