Singleton Struct

template <typename T> struct Qul ::Singleton

Inherit from this class to expose the C++ class or struct to the QML as a singleton. 更多...

Header: #include <qul/singleton.h>
Since: Qt Quick Ultralite 1.0
继承: Qul::Object

This struct was introduced in Qt Quick Ultralite 1.0.

静态公共成员

T & instance ()

详细描述

The qmlinterfacegenerator tool will generate QML type with pragma Singleton directive for a class derived from the singleton.

This class use the Curiously recurring template pattern (CRTP) and the template parameter needs to be the derived type.

Minimal example:

struct MySingleton : public Qul::Singleton<MySingleton>
{
    Property<int> someProperty;
    int someFunction(int param);
};
							

Above example is just fine if you are not going to use Singleton from C++ code. Otherwise you should make it a bit more complete:

struct MySingleton : public Qul::Singleton<MySingleton>
{
    // Create friendship for a base class to be able to access private constructor
    friend class Qul::Singleton<MySingleton>
    Property<int> someProperty;
    int someFunction(int param);
private:
    MySingleton() {}                                // Private constructor
    MySingleton(const MySingleton &);              // Non copy-constructible
    MySingleton &operator=(const MySingleton &);   // Non copyable
};
							

Now MySingleton can be safely used both form QML:

Item {
    property int otherProperty: MySingleton.someProperty
}
							

and from C++:

void someFunction() {
    MySingleton.instance().someProperty.setValue(42);
}
							

另请参阅 Singletons .

成员函数文档编制

[static] T &Singleton:: instance ()

Returns a reference to the singleton instance.