我有一个创建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 !!
}
}在parent of the created object. However, when I print them from QML, theparenthas anulland the properties areundefined`.上下文中,我可以正确地打印我设置的属性值以及C++
我从C++和QML打印了创建对象的入口,我得到了相同的地址。我不明白是什么导致了这种行为。
谢谢你的帮助。
发布于 2015-07-14 12:16:54
我通过在C++代码中添加以下代码行解决了这个问题:
mainObject_->setParentItem(qobject_cast<QQuickItem*>(parent)); https://stackoverflow.com/questions/31405577
复制相似问题