Question

I'm trying to put 5 buttons in my window, aligned in a row, and each button should have equal width, while occupying all the available space in the parent. Here's how I'm trying (fails):

Row {
      id: toolbar
      width: 300
      height: 80

      Button {
        text: "left"
      }

      Button {
        text: "right"
      }

      Button {
        text: "tab"
      }

      Button {
        text: "home"
      }

      Button {
        text: "end"
      }
}

In this example, the Button items won't be resized to fit in their parent. I would like to see each Button get 1/5 of their parent's width. Obviously, using Row isn't enough.

Also, using:

width: parent.width / parent.children.count

in each Button fails, as parent.children.count is undefined. One could use Component.onCompleted to set the width, when everything is already prepared, but there has to be a better way.

Is there an option of Row which enforces a width on its children? Or what other layout option is there?

Was it helpful?

Solution

Personnally when doing this I use a Repeater and a ListModel or an array of text so that you can easily know how many Button you are going to have and resize them properly

ListModel {
    id: modelButtons
    ListElement { buttonText: "left" }
    ListElement { buttonText: "right" }
    ListElement { buttonText: "tab" }
    ListElement { buttonText: "home" }
    ListElement { buttonText: "end" }
}

Row {
    id: toolbar
    width: 300
    height: 80

    Repeater {
        id: repeaterButton
        model: modelButtons
        delegate: Button {
            width: toolbar.width / repeaterButton.model.count
            text: buttonText
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top