jf192210
jf192210

Reputation: 157

How to dynamically append elements to ListModel from exterior scope

Suppose I had the Component

Component {
  id: myComp1

  Item {
    id: item

    ListView {
      id: listView
      model : ListModel { id: listModel } 
      delegate : RowLayout { /* display model data*/ } 
      
      Component.onCompleted {
        // get data from server ... 
        model.append(dataFromServer)
      }

    }
  }
}

Then I have a second Component, which is another page in the stack, and I want to use this component to update mycomp1, i.e:

Component {
  id: myComp2
  Button {
    onClicked: { 
      myComp1.item.listView.listModel.append(someNewData) // want to be able to do this
    }  
  }
}

And these components are tied together in a StackView

Now, this doesnt seem to work since myComp2 cant seem to access the necessary scope to update the model of myComp1. Is there any way around this?

Thanks for the help.

Upvotes: 0

Views: 427

Answers (1)

JarMan
JarMan

Reputation: 8287

The problem is that a Component is like a type declaration. It does not define an instance of an object, so you cannot access its members.

You could pull the ListModel outside of that Component so that both Components can access it.

ListModel {
    id: listModel
}

Component {
    id: comp1
    ListView { model: listModel }
}

Component {
    id: comp2
    Button {
        onClicked: { listModel.append(someNewData) }
    }
}

Upvotes: 1

Related Questions