本页内容

C

Qul::Singleton Struct

template <typename T> struct Qul::Singleton

继承自该类,可将 C++ 类或结构体作为单例暴露给 QML。更多...

Header: #include <qul/singleton.h>
Since: Qt Quick Ultralite 1.0
Inherits: Qul::Object and Qul::SingletonBase

静态公共成员

T &instance()

详细说明

qmlinterfacegenerator 工具将为从该单例类派生的类生成带有pragma Singleton指令的 QML 类型。

该类使用“奇异递归模板”模式(CRTP),且模板参数必须是派生类型。

最简单的示例:

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

如果您不打算在 C++ 代码中使用 Singleton,上面的示例完全没问题。否则,您应该将其完善一些:

struct MySingleton : Qul::Singleton<MySingleton>
{
    // Create friendship for a base class to be able to access private constructor
    friend struct 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
};

现在,MySingleton 既可以在QML中安全地使用:

Item {
    property int otherProperty: MySingleton.someProperty
}

和 C++ 代码中:

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

另请参阅 “单例”和“在 QML 中定义单例”。

成员函数文档

[static] T &Singleton::instance()

返回对单例实例的引用。

在某些 Qt 许可下可用。
了解更多信息。