How to create mupltiple qml components in a loop

qml
11,023

Solution 1

A loop is an imperative code, so it's not QML but Javascript or C++. So sure, you can do it (for example by embedding a Qt.createComponent() call in a JS loop) but in QML, it's a better thing to think declarative, which mean you don't 'do' things, you 'define' things :

import QtQuick 2.0

Rectangle {
    id: base;
    width: 400;
    height: 800;

    Column {
        spacing: 5; // a simple layout do avoid overlapping

        Repeater {
            model: 10; // just define the number you want, can be a variable too
            delegate: Rectangle {
                width: 200;
                height: 20;
                color: "white";
                border { width: 1; color: "black" }
                radius: 3;

                TextInput {
                    anchors.fill: parent;
                }
            }
        }
    }
}

This way it's really more powerfull and much cleaner from a QML point of view !

Solution 2

Look into the QML Repeater element http://doc.qt.io/qt-4.8/qml-positioners.html

Share:
11,023
itapadar
Author by

itapadar

Updated on June 18, 2022

Comments

  • itapadar
    itapadar about 2 years

    I wish to create a qml window with 100 textedit's for an example, how do I create it within a loop? Is that possible?