Qt / QML qmlRegisterType vs. setContextProperty(difference) [英] Qt/QML qmlRegisterType vs. setContextProperty (difference)

查看:2040
本文介绍了Qt / QML qmlRegisterType vs. setContextProperty(difference)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Qt / QML应用程序中(这段代码通常位于QtCreator项目的 main.cpp 中),将C ++类暴露给QML的方法有以下区别: / p>

  qmlRegisterType< UePeopleModel>(com.example,
1,
0,
UePeopleModel);

  engine.rootContext() - > setContextProperty(uePeopleModel,
uePeopleModel);

解决方案

qmlRegisterType



有时一个QObject派生类可能需要注册到QML类型系统,可实例化类型。



如果要在一个或多个具有不同属性的qml文件中重用QObject派生类,请使用qmlRegisterType。 QML负责初始化此寄存器类。



有关更多帮助,请参阅此处。
从C ++定义QML类型



setContextProperty



使用setContextProperty,当您想使用单个全局类访问或来自QML。这里你需要创建这个类对象之前使用setContextProperty()。



注意:由于在QML中求值的所有表达式都在特定上下文中求值,如果上下文被修改,则该上下文中的所有绑定都将被重新求值。因此,应该在应用程序初始化之外谨慎使用上下文属性,因为这可能会导致应用程序性能下降。



有关更多帮助,请参阅此处。
将C ++对象嵌入到QML


In Qt/QML application (this code usually resides in main.cpp of QtCreator project), what is the difference between following ways of exposing C++ class to QML:

qmlRegisterType<UePeopleModel>("com.example",
                               1,
                               0,
                               "UePeopleModel");

and

engine.rootContext()->setContextProperty("uePeopleModel",
                                         uePeopleModel);

?

解决方案

qmlRegisterType :

"Sometimes a QObject-derived class may need to be registered with the QML type system but not as an instantiable type."

Use qmlRegisterType, if you want reuse a QObject-derived class with in one or more than one qml file with different property. QML is responsible for initialization of this register class.

See this for more help. Defining QML Types from C++

setContextProperty :

Use setContextProperty, When you want to use a single global class to access to or from QML. Here You need create this class object before use setContextProperty().

Note: Since all expressions evaluated in QML are evaluated in a particular context, if the context is modified, all bindings in that context will be re-evaluated. Thus, context properties should be used with care outside of application initialization, as this may lead to decreased application performance.

See this for more help. Embedding C++ Objects into QML

这篇关于Qt / QML qmlRegisterType vs. setContextProperty(difference)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆