Accesing a qml item from a ListModel



  • hello,

    i have the following qml code:

    @
    Rectangle
    {
    id: bgRect
    width: 800
    height: 600
    objectName: "asd"
    Component
    {
    id: myDelegate

        Item
        {
            id:itm
            objectName: "item"+index;
            width: 40*(index+1)
            height: 40
            x:60-((index+1)*20)
    
            Rectangle
            {
    
                anchors.centerIn: parent
                anchors.fill: parent
                anchors.margins: 1
                radius: 5
                color: "lightsteelblue"
    
                Text
                {
                    text: "Disc "+model.ring
                    color: "black"
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.verticalCenter:  parent.verticalCenter
                }
    
                MouseArea
                {
                    anchors.fill: parent
                    onClicked:
                        console.log("objectName "+itm.objectName)
                }
    
                Component.onCompleted:
                    console.log(itm.objectName)
            }
        }
    }
    
    ListView
    {
        id: myListView
        anchors.fill: parent
        delegate: myDelegate
        model: myModel
        orientation: ListView.Vertical
        boundsBehavior: Flickable.StopAtBounds
    }
    

    }
    @

    and i am trying to acces the " objectName: "item"+index; " --line 16-- element with the following cpp code:

    @
    QObject object = (QObject)view->rootObject();
    QObject myObject = object->findChild<QObject>("item0");
    if(myObject)
    {
    //myObject->setProperty("x","50");
    qDebug()<<"myObject was created";
    myObject->setProperty("x","150");
    myObject->setProperty("color","green");
    }
    @

    and no luck so far, although, i can acces the "asd" rectangle from cpp. Please help.

    Thank you



  • Hello,

    i would go ahead and add an objectName to your Model and access its method get(int index):
    "object ListModel:.get()":http://qt-project.org/doc/qt-5.0/qtqml/qml-qtquick2-listmodel.html#get-method

    Otherwise you could try to access your Models child instead.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.