首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置从C++创建的qml对象的父对象不起作用

设置从C++创建的qml对象的父对象不起作用
EN

Stack Overflow用户
提问于 2015-07-14 11:41:00
回答 1查看 1.4K关注 0票数 0

我有一个创建QML对象的C++类,它需要五个参数:

代码语言:javascript
复制
//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中使用它,如下所示:

代码语言:javascript
复制
 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打印了创建对象的入口,我得到了相同的地址。我不明白是什么导致了这种行为。

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-14 12:16:54

我通过在C++代码中添加以下代码行解决了这个问题:

代码语言:javascript
复制
mainObject_->setParentItem(qobject_cast<QQuickItem*>(parent));   
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31405577

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档