从 C++ 设置创建的 qml 对象的父对象不起作用
Setting parent of a created qml object from C++ is not working
我有一个创建 QML 对象的 C++ class,它需要五个参数:
//prototype
// Q_INVOKABLE QQuickItem *createQmlObject(QObject *parent, QString path, QString id="", int x=0, int y=0);
QQuickItem * QmlItemCreator::createQmlObject(QObject* parent,QString path,QString id,int x,int y)
{
QQmlEngine engine;
QQmlComponent component(&engine, QUrl::fromLocalFile(path));
QQuickItem * mainObject_;
if(component.isError())
{
qWarning() << "QmlItemCreator::createQmlObject The QMLComponent for "
<< path << " has errors: " << component.errorString();
}
else if (component.isReady())
{
mainObject_ = qobject_cast<QQuickItem*>(component.create());
QQmlEngine::setObjectOwnership(mainObject_, QQmlEngine::JavaScriptOwnership);
mainObject_->setProperty("id",id);
mainObject_->setProperty("x",x);
mainObject_->setProperty("y",y);
mainObject_->setParent(parent);
// qDebug()<<mainObject_<<" "<<mainObject_->parent()<<" "<<mainObject_->property("x");
}
else
{
componentComplete();
}
return mainObject_;
}
我在QML中使用如下:
Item{
id: idRoot
Component.onCompleted:
{
var obj = qmlCreator.createQmlObject(idRoot,"path/test.qml")
console.log(obj.parent)// print null !!
}
}
在 C++ 上下文中,我可以正确打印我设置的属性值,以及 parent of the created object. However, when I print them from QML, the
parenthas a
nulland the properties are
undefined`。
我打印了从 C++ 和 QML 创建的对象的地址,我得到了相同的地址。我不明白是什么导致了这种行为。
感谢您的帮助。
我通过在 C++ 代码中添加以下代码行解决了这个问题:
mainObject_->setParentItem(qobject_cast<QQuickItem*>(parent));
我有一个创建 QML 对象的 C++ class,它需要五个参数:
//prototype
// Q_INVOKABLE QQuickItem *createQmlObject(QObject *parent, QString path, QString id="", int x=0, int y=0);
QQuickItem * QmlItemCreator::createQmlObject(QObject* parent,QString path,QString id,int x,int y)
{
QQmlEngine engine;
QQmlComponent component(&engine, QUrl::fromLocalFile(path));
QQuickItem * mainObject_;
if(component.isError())
{
qWarning() << "QmlItemCreator::createQmlObject The QMLComponent for "
<< path << " has errors: " << component.errorString();
}
else if (component.isReady())
{
mainObject_ = qobject_cast<QQuickItem*>(component.create());
QQmlEngine::setObjectOwnership(mainObject_, QQmlEngine::JavaScriptOwnership);
mainObject_->setProperty("id",id);
mainObject_->setProperty("x",x);
mainObject_->setProperty("y",y);
mainObject_->setParent(parent);
// qDebug()<<mainObject_<<" "<<mainObject_->parent()<<" "<<mainObject_->property("x");
}
else
{
componentComplete();
}
return mainObject_;
}
我在QML中使用如下:
Item{
id: idRoot
Component.onCompleted:
{
var obj = qmlCreator.createQmlObject(idRoot,"path/test.qml")
console.log(obj.parent)// print null !!
}
}
在 C++ 上下文中,我可以正确打印我设置的属性值,以及 parent of the created object. However, when I print them from QML, the
parenthas a
nulland the properties are
undefined`。
我打印了从 C++ 和 QML 创建的对象的地址,我得到了相同的地址。我不明白是什么导致了这种行为。
感谢您的帮助。
我通过在 C++ 代码中添加以下代码行解决了这个问题:
mainObject_->setParentItem(qobject_cast<QQuickItem*>(parent));