在 C++ 中创建 QML 元素? [英] Create QML Element in C++?

查看:46
本文介绍了在 C++ 中创建 QML 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

我使用 .qml 文件将初始界面加载到 QQuickView 中.然后我想像 Image 一样添加 QML typescode> 或 Text 到使用 C++ 的界面.

I load an initial interface into a QQuickView using a .qml file. I then want to add QML types like an Image or Text to the interface using C++.

我知道我可以从 C++ 操作现有元素,但如何创建新类型并添加它们?

I know I can manipulate existing elements from C++ but how can I create new types and add them?

推荐答案

不幸的是,文档有点过时(使用 Qt4 api),但是如果您阅读了从 C++ 加载 QML 组件 这里:https://doc.qt.io/qt-4.8/qtbinding.html

Unfortunately the docs are a bit out-of-date (uses Qt4 api), but If you read section Loading QML Components from C++ here: https://doc.qt.io/qt-4.8/qtbinding.html

那么你应该有类似的东西(使用 Qt5 api):

Then you should have something like (with Qt5 api):

QQuickView view;
view.setSource(QUrl::fromLocalFile("MyView.qml"));
QQmlComponent component(view.engine()
        , QUrl::fromLocalFile("MyItem.qml"));
QObject *object = component.create();

这为您提供了来自 .qml 文件的 QObject,但缺少的是如何将其添加到视图中.在 qml 中,项目不会被绘制,除非它们是视图的父级.一种方法是将项目添加到根上下文,如下所示:

This gives you a QObject from a .qml file, but what's missing is how to add this to the view. In qml, items won't get drawn unless they are parented to the view. One way of doing this is to add the item to the root context, like so:

QQmlProperty::write(object, "parent"
                    , QVariant::fromValue<QObject*>(view.rootObject()));

另外,请注意(再次来自上面的链接):您应该始终使用 QObject::setProperty()、QDeclarativeProperty 或 QMetaProperty::write() 来更改 QML 属性值,以确保 QML 引擎知道属性变化".

Also, note (again from the above link): "You should always use QObject::setProperty(), QDeclarativeProperty or QMetaProperty::write() to change a QML property value, to ensure the QML engine is made aware of the property change".

接下来,我们需要设置项目的所有权,否则 JavaScript 垃圾处理程序可以删除您的项目,您可以随机分段错误.

Next, we need to set the ownership of the item, otherwise the JavaScript garbage handler can delete your item and you can seg fault randomly.

QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);

最后需要记得删除对象object".由于它是一个 QObject,你应该使用:

Finally, you need to remember to delete the object "object". Since it's a QObject you should use:

object->deleteLater();

希望对某人有所帮助!

这篇关于在 C++ 中创建 QML 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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