用单体类型注册单体对象到qml中

来源:互联网 发布:瑞斯康微电子知乎 编辑:程序博客网 时间:2024/05/21 09:22

一个单体对象不需要用户手动构造实例就可以将属性,信号,方法在命名空间里暴露。QObject单体类型是非常有效和安全的方式提供函数和全局属性值。单体对象不能和QQmlContext联合访问引擎的内容。单体对象有QQmlEngine构造,随着QQmlEngine销毁而随之销毁。

1、QJSValue 注册一个Value属性

static QJSValue getCountStatic(QQmlEngineengine,QJSEnginescriptEngine){Q_UNUSED(engine);static int seedValue = 5;QJSValue example = scriptEngine->newObject();example.setProperty("someProperty",++seedValue);return example;}

注册:

qmlRegisterSingletonType("Qt.example.signle",1,0,"MyApi",getCountStatic);

//脚本中使用
property var somebee:ExampleSingle.MyApi.someProperty
2、QObject*

class SingleObject : public QObject{Q_OBJECTQ_PROPERTY(int someindex READ someindex WRITE setSomeIndex NOTIFY indexChange)public:SingleObject(QObjectparent = 0);~SingleObject();int someindex() const;void setSomeIndex(int index); Q_INVOKABLE int doSomething(); signals:void indexChange(int index);protected:private:int m_someindex;};

使用Q_INVOKABLE注册

static QObjectgetQtObject(QQmlEngineengine,QJSEnginescriptEngine){Q_UNUSED(engine);Q_UNUSED(scriptEngine);SingleObjectobj = new SingleObject;return obj;}
注册:qmlRegisterSingletonType<SingleObject>("Qt.example.signle",1,0,"MyQtApi",getQtObject);

脚本调用:

import MessagePerson 1.0import Qt.example.signle 1.0 as ExampleSingleMessage{    author:"王bull"authorDate:new Date()property var somebee:ExampleSingle.MyApi.somePropertyproperty var qtbee:ExampleSingle.MyQtApi.doSomething()}
直接上代码了,会使用即可,C++单体在脚本中的调用介绍到这里了。


0 0
原创粉丝点击