У меня есть C++ класс, который создает объект QML, он принимает пять параметров:Установка родителем созданного объекта 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, и у меня есть тот же адрес. Я не понимаю, что вызывает подобное поведение.
Благодарим за помощь.
Я использую Qt 5.5.0 на окнах – Mido