一个单体对象不需要用户手动构造实例就可以将属性,信号,方法在命名空间里暴露。QObject 单体类型是非常有效和安全的方式提供函数和全局属性值。单体对象不能和QQmlContext联合访问引擎的内容。单体对象有QQmlEngine构造,随着QQmlEngine销毁而随之销毁。
1、QJSValue 注册一个Value属性
static QJSValue getCountStatic(QQmlEngine* engine,QJSEngine* scriptEngine){ 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.someProperty2、 QObject *
class SingleObject : public QObject { Q_OBJECT Q_PROPERTY(int someindex READ someindex WRITE setSomeIndex NOTIFY indexChange) public: SingleObject(QObject* parent = 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 QObject* getQtObject(QQmlEngine* engine,QJSEngine* scriptEngine){ Q_UNUSED(engine); Q_UNUSED(scriptEngine); SingleObject* obj = new SingleObject; return obj; }注册: qmlRegisterSingletonType < SingleObject >( "Qt.example.signle" ,1,0, "MyQtApi" , getQtObject );
脚本调用:
import MessagePerson 1.0 import Qt.example.signle 1.0 as ExampleSingle Message{ author:"王bull" authorDate:new Date() property var somebee:ExampleSingle.MyApi.someProperty property var qtbee:ExampleSingle.MyQtApi.doSomething() }直接上代码了,会使用即可,C++单体在脚本中的调用介绍到这里了。