FuzzyWombatSoup
FuzzyWombatSoup

Reputation: 13

QML - Using ListView with dynamically generated ListElement

I have this QML with the ListView:

import QtQuick 2.0
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.0
import smah.light 1.0
import smah.zone 1.0

Page {

    id: page
    property var lights: ({})
    property var lightNames: ([])
    title: "Device control"

    ListView {
        id: lightList
        anchors.fill: parent
        model: listModel
        delegate:
            Rectangle{
            width: lightList.width
            height: lightList.height / 8
        }
    }

    ListModel {
        id: listModel
        dynamicRoles: true
        Component.onCompleted: {
            listModel.clear()
            for (var i=0; i<lights.length; i++) {
                var component = Qt.createComponent("LightControls.qml",listModel)
                listModel.append(component.createObject(lightList, {light_name: lights[i].getName }))
            }
        }

    }
}

The LightControls.qml is:

import QtQuick 2.0
import QtQuick.Controls 2.5
import smah.light 1.0

Rectangle {
    id: rectangle
    property int light_type: 0
    property int light_id: 0
    property var light_name: "_DEF"
    width: parent.width
    height: 50
    color: "#040000"

    Text {
        id: txtName
        color: "#fefdfd"
        text: qsTr(light_name)
        anchors.left: parent.left
        anchors.leftMargin: 15
        anchors.top: parent.top
        anchors.topMargin: 8
        font.pixelSize: 20
    }

    Slider {
        id: slider
        x: 179
        y: 10
        width: 302
        height: 22
        value: 0.5
    }

    Text {
        id: txtValue
        x: 517
        width: 45
        height: 15
        color: "#ffffff"
        text: qsTr("Text")
        anchors.top: parent.top
        anchors.topMargin: 8
        font.pixelSize: 20
    }

    Button {
        id: button
        x: 694
        y: 10
        text: qsTr("Button")
    }
}

I want a clean scrollable list with each of these items generated shown in it. I've looked at using a Repeater instead of the list, but I'll have more elements in the list than are desired on the screen. When running the program, everything is garbled into a single incoherent mess:

enter image description here

Upvotes: 1

Views: 999

Answers (1)

Mitch
Mitch

Reputation: 24416

There are a few larger issues with your code:

  1. You're trying to add a visual item to a ListModel, which expects ListElement objects. You can use append() to add rows to a ListModel.
  2. Your root delegate item is a Rectangle, which doesn't manage the layout of its children. Use a RowLayout or Row instead.
  3. Your delegate should be delegate: LightControls {}.

Upvotes: 2

Related Questions