Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QML GridLayout Variable Column For Varied Sized Items



  • GridLayout {
            id: grid
            anchors.horizontalCenter: parent.horizontalCenter
    //        width: 800
    //        columns: width > 200 ? 3 : 1
    
            onWidthChanged: {
                console.log("width:",childrenRect.width)
            }
    
            Repeater {
                id: repeater
                model: someModel
                delegate: Label {
                    text: modelData
                }
            }
        }
    

    My code is similar to this. Label text has varied sizes so I cannot hardcode columns attribute of GridLayout. If text is too long, there should be maximum 1 column or if text is small there can be 5 columns for example. This becomes a problem considering I have more than 10-15 rows.

    If I put a function for columns, it doesn't work well because GridLayout adds items one by one therefore there are many width changes until its done. For example it starts from 500px and goes to 1300px so if my page has maximum 1000px of width, I cannot set it like that.

    I am open to any suggestion. You don't have to be 100% confident, I can try different things if you have an idea.



  • I found solution.

    Repeater {
                    id: repeater
                    model: someModel
                    delegate: MyRadioButton {
                        text: modelData
                    }
    
                    onItemAdded: {
                        if (item.width > maxWidth) {
                            maxWidth = item.width
                            var quotient = Math.floor(1000/maxWidth);
                            grid.columns = quotient
                        }
                    }
                }
    


  • I found solution.

    Repeater {
                    id: repeater
                    model: someModel
                    delegate: MyRadioButton {
                        text: modelData
                    }
    
                    onItemAdded: {
                        if (item.width > maxWidth) {
                            maxWidth = item.width
                            var quotient = Math.floor(1000/maxWidth);
                            grid.columns = quotient
                        }
                    }
                }
    

Log in to reply