簡介
qmlRegisterSingletonType是一個帶回調的註冊函數,作用是將C++類註冊到QML系統中並帶一個回調函數。
該回調函數在每次調用doSomething時候調用,然後在回調函數裏產生新的C++ Class提供給QML調用,此方法可以實現C++ Class 的動態加載和動態切換。
範例
注:該範例摘選自官方說明手冊,本人尚未實驗過在此僅作說明參考,介紹是依據代碼自己理解的,若有誤歡迎大神指出。
// 首先定義一個基於OBject的類,也就是準備註冊到QML的類
class SingletonTypeExample : public QObject
{
Q_OBJECT //必須要
Q_PROPERTY (int someProperty READ someProperty WRITE setSomeProperty NOTIFY somePropertyChanged)//重定義變量/讀/寫/改方法
public:
SingletonTypeExample(QObject* parent = 0)
: QObject(parent), m_someProperty(0)
{
}
~SingletonTypeExample() {}
Q_INVOKABLE int doSomething() { setSomeProperty(5); return m_someProperty; } //Q_INVOKABLE 方便QML系統回調
int someProperty() const { return m_someProperty; }
void setSomeProperty(int val) { m_someProperty = val; emit somePropertyChanged(val); }
signals:
void somePropertyChanged(int newValue);
private:
int m_someProperty;
};
// 第二步定義一個回調類指針,用於接收回調.
static QObject *example_qobject_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
SingletonTypeExample *example = new SingletonTypeExample();
return example;
}
使用:
在C++中註冊類
qmlRegisterSingletonType<SingletonTypeExample>("Qt.example.qobjectSingleton", 1, 0, "MyApi", example_qobject_singletontype_provider);
在QML中使用
import QtQuick 2.0
import Qt.example.qobjectSingleton 1.0
Item {
id: root
property int someValue: MyApi.someProperty
Component.onCompleted: {
someValue = MyApi.doSomething()
}
}