我有一个创建QML对象的C ++类,它需要五个参数:
//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
父has a
null and the properties are
undefined`。
我从C ++和QML打印了创建对象的地址,我有相同的地址。我不明白是什么导致了这种行为。
感谢您的帮助。
答案 0 :(得分:0)
我通过在C ++代码中添加以下代码行解决了这个问题:
mainObject_->setParentItem(qobject_cast<QQuickItem*>(parent));