簡體   English   中英

QML - 將 ListView 與動態生成的 ListElement 結合使用

[英]QML - Using ListView with dynamically generated ListElement

我有這個 QML 和 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 }))
            }
        }

    }
}

LightControls.qml 是:

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")
    }
}

我想要一個干凈的可滾動列表,其中顯示了生成的每個項目。 我考慮過使用 Repeater 代替列表,但列表中的元素比屏幕上所需的要多。 運行程序時,一切都亂碼成一個不連貫的混亂:

在此處輸入圖像描述

您的代碼存在一些較大的問題:

  1. 您正在嘗試將視覺項目添加到ListModel ,它需要ListElement對象。 您可以使用append()將行添加到ListModel
  2. 您的根委托項是一個Rectangle ,它不管理其子項的布局。 請改用RowLayoutRow
  3. 您的代表應該是delegate: LightControls {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM