获取 c++ QML 中的对象并在 javascript 中使用它
我正在制作一个应用程序,在其中我想从 C++ 源代码中的 QML 调用一个函数,并且该 C++ 函数返回我和对象,我可以将它与 QML 的 javascript 部分中的相同属性一起使用。我已经建立了联系和一切。我尝试发送 QVariantMap 并尝试在 javascript 中使用该对象,但我没有获取该对象的属性
I'm making an application in which I'd like to call a function from QML in C++ source, and that c++ function to return me and object which I can use it with the same properties in the javascript part of QML. I've made the connection and everything. I've tried to send a QVariantMap and tried to use that object in javascript, but I don't get the properties of that object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两种方法可以将基于 QObject 的类型从 C++ 导出到 QML:
There are two ways for exporting QObject based types from C++ to QML:
要公开的类必须继承自 QObject(或 QDeclarativeItem,如果它们是 UI 组件),并且在加载 QML 代码之前,您必须在 main() 或 Qt 插件中注册它们的类型。
看看 http://developer .qt.nokia.com/doc/qt-4.7/declarative-tutorials-extending-chapter1-basics.html
Your classes to be exposed have to inherit from QObject (or QDeclarativeItem if they are UI components) and you will have to register their types in your main() or in a Qt plugin before loading the QML code.
Have a look at http://developer.qt.nokia.com/doc/qt-4.7/declarative-tutorials-extending-chapter1-basics.html
要将对象作为函数返回值从 C++ 传递到 QML,返回值类型需要是 QVariant,而不是 QVariantMap,即使这是 C++ 代码中的类型。因此,只需将您的
initialize
函数签名更改为而不更改任何其他内容,然后您就可以访问属性。
关于您后来关于想要调用返回对象的方法的评论,这是不可能的;返回的对象只是一组名称-值对。如果您希望对象具有
id
属性,则需要先将带有该键的值插入
到 C++ 中的QVariantMap
中返回它。To pass an object from C++ to QML as a function return value, the return value type needs to be
QVariant
, notQVariantMap
, even though that is the type in the C++ code. So just change yourinitialize
function signature towithout changing anything else, and then you can access the properties.
Regarding your later comment on wanting to call methods on that returned object, that is not possible; the returned object is just a set of name-value pairs. If you want the object to have, say, an
id
property, you need toinsert
a value with that key to theQVariantMap
in C++ before returning it.