Qt World Summit: Submit your Presentation

Adding Components Dynamically

  • Hi,

    here's what I'm trying to do.

    I have a component of type A (a rectangle) and a component of type B (another rectangle).

    I want to dynamically add a few component A to a ListView. Then, I want to dynamically add a few components B to each item A in the ListView.

    Also, I have a 'controller' qobject that is registered and is used to add A's and B's.

    Here's a visual reprensentation of the structure I'm trying to build:

        - A_1:
              - B_11
              - B_12
              - B_13
        - A_2:
              - B_21
              - B_12

    I have tried a lot of things.

    My 'last' attempt is a ListView with a DelegateModel and I add models using append (shown below)

    ListView {
       model: DelegateModel {
          model: ListModel {
             id: listModel
          delegate: A {
    // Code used to add an item

    This works fine, but then I'm stuck trying to figure out how to dynamically add components B to each item.
    I have something like this (which doesn't work):

     onBAdded: {                                                         
                for (var i = 0; i < listModel.count; i++) {
                    var item = myModel.items.get(i) 
                    // Each A's have id (aName)
                    if (item.model.aName === aName) {
                        var component = Qt.createComponent("B.qml")
                        // This doesn't work (nothing is shown, if I replace item with root, it shows)
                        component.createObject(item, {
                                                                x: 10,
                                                                y: 10,
                                                                z: 100

    I might be going totally wrong about this whole thing. I feel this should be a very simple thing to do.

Log in to reply