Qt C++注册单例到Qml
1.说明:
普通类对象
C++类注册到Qml中(qmlRegisterType),Qml中添加该组件进行调用,如下:
MyCppClass{
id: MyCppClass //通过id调用该类对应的方法
}
单例对象:
C++创建单例类。
定义QQmlEngine的方法(参见帮助文档)
使用qmlRegisterSingletonType注入Qml中。
Qml中import MyCppClass,就可以直接通过MyCppClass调用类对象的方法。
源码如下:
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; }
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;
};
// Second, define the singleton type provider function (callback).
static QObject *example_qobject_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
SingletonTypeExample *example = new SingletonTypeExample();
return example;
}
// Third, register the singleton type provider with QML by calling this function in an initialization function.
qmlRegisterSingletonType<SingletonTypeExample>("Qt.example.qobjectSingleton", 1, 0, "MyApi", example_qobject_singletontype_provider);