-->

Removing empty spaces when the delegate is not vis

2020-07-25 10:27发布

问题:

I am trying to use the following model and delegate components in a grid view. The model has a boolean role vis which turns the visible property of the delegate on or off. Later on I intend to bind this vis property to my backend.In this example the green button does not show up as intended but leaves an empty space between red and brown buttons. How do I get rid of the empty space. I just want the brown button to be next to red button

This is my model component

ListModel { 
    ListElement {
        rectcolor:"red"
        vis:true
    }
    ListElement {
        rectcolor:"green"
        vis:false
    }
    ListElement
    {rectcolor:"brown"
     vis:true
    }
}

This is my delegate

Rectangle {
    width: 100
    height: 62
    visible:model.vis
    Button{color:model.rectcolor}
}

回答1:

For anyone still interested in hiding delegates of a GridView without a filter model, the solution is to create a Grid instead, inside a Flickable element. This will even allow your grid to have animations when hiding delegates.

For a live example on Grid, check the Qt QML example positioners.

ListModel {
    id: model
    ListElement {
        rectcolor:"red"
        vis:true
    }
    ListElement {
        rectcolor:"green"
        vis:false
    }
    ListElement {
        rectcolor:"brown"
        vis:true
    }
}    

Flickable {
    anchors.fill: parent

    contentWidth: width
    contentHeight: grid.height

    clip: true

    Grid {
        id: grid
        width: parent.width
        height: childrenRect.height + 40
        rowSpacing: 10
        columnSpacing: 10

        property int cellSize: 140

        columns: {
            Math.floor(width / 150)
        }

        move: Transition {
            NumberAnimation { properties: "x,y"; duration: 200; easing.type: Easing.OutSine }
        }

        Repeater {
            model: model
            delegate: Rectangle {
                color: rectColor
                visible: vis
            }
        }
    }
}


回答2:

if you want to exclude item from ListView(or GridView, etc) set visible and enable variables in delegate to false



回答3:

you may hide delegate by resizing him to zero (as variant of fast and dirty method)

ListView {
    anchors.fill: parent
    delegate: Rectangle {
        width: model.vis ? 100 : 0
        height: model.vis ? 62 : 0
        visible:model.vis
        Rectangle {
            anchors.fill: parent
            color: model.rectcolor
        }
    }
    model: ListModel {
        ListElement {
            rectcolor: "red"
            vis:true
        }
        ListElement {
            rectcolor: "green"
            vis:false
        }
        ListElement {
         rectcolor: "brown"
         vis:true
        }
    }
}


标签: gridview qml