Create QML object from C++ with specified properties(从C++创建具有指定属性的QML对象)
问题描述
从C++动态实例化QML对象是well documented,但我找不到的是如何用它的属性的预先指定的值来实例化它。
例如,我正在从C++创建一个稍微修改过的SplitView,如下所示:
QQmlEngine* engine = QtQml::qmlEngine( this );
QQmlComponent splitComp( engine, QUrl( "qrc:/qml/Sy_splitView.qml" ) );
QObject* splitter = splitComp.create();
splitter->setProperty( "orientation", QVariant::fromValue( orientation ) );
我遇到的问题是,在之后指定SplitView的orientation会导致其内部布局中断。那么,有没有办法用已经指定的orientation来创建SplitView呢?
或者,我可以在单独的文件中创建SplitView的水平和垂直版本,并在运行时实例化适当的版本--但这不是很优雅。
更新
我找到QQmlComponent::beginCreate(QQmlContext* publicContext):
QQmlEngine* engine = QtQml::qmlEngine( this );
QQmlComponent splitComp( engine, QUrl( "qrc:/qml/Sy_splitView.qml" ) );
QObject* splitter = splitComp.beginCreate( engine->contextForObject( this ) );
splitter->setProperty( "orientation", QVariant::fromValue( orientation ) );
splitter->setParent( parent() );
splitter->setProperty( "parent", QVariant::fromValue( parent() ) );
splitComp.completeCreate();
但出人意料地没有效果。
推荐答案
对于仍然对此问题感兴趣的人,在Qt 5(因此Qt 6)中,您还可以使用QQmlContext和QQmlContext::setContextProperty()来设置外部属性(在您的情况下是orientation):
QQmlEngine engine;
QQmlContext *context = new QQmlContext(engine.rootContext());
context->setContextProperty("myCustomOrientation", QVariant::fromValue(orientation));
// you can use a 'myCustomOrientation' property inside Sy_splitView.qml, e.g.
// `orientation: myCustomOrientation`
QQmlComponent splitComp(&engine, QUrl("qrc:/qml/Sy_splitView.qml"));
QObject* splitter = splitComp.create(context);
这应该允许您不摆弄beginCreate和completeCreate。
这篇关于从C++创建具有指定属性的QML对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从C++创建具有指定属性的QML对象
基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
