Share equally the horizontal space in a QML Row
Solution 1
The minimum width of a button itself is the implicitWidth property of its Text element.
One solution to your problem might be to add code in the Component.onCompleted handler, i.e. code that is executed after the repeater has created its items, and then sum up these implicitWidth properties of each of the repeater's item (which you can get by using its itemAt(index) function).
These kinds of dynamic layout is a bit cumbersome in QML still, which will get much better in Qt 5.1 with the introduction of Qt Quick Layouts
Solution 2
If you don't want to use QtQuick.Layouts as they are not really ready yet, you can use this :
Rectangle {
id: buttonBar;
color: "#DDDDDD";
height: 30;
width: (buttonColumn.width + 20 + buttonRow.spacing) * buttonsRepeater.count;
anchors {
bottom: parent.bottom;
left: parent.left;
}
Column {
id: buttonColumn;
visible: false;
Repeater {
model: buttonsModel;
delegate: Text {
text: model.text;
}
}
}
Row {
id: buttonRow;
anchors.fill: parent;
property real itemWidth : ((width + spacing) / buttonsRepeater.count) - spacing;
Repeater {
id: buttonsRepeater;
model: buttonsModel;
delegate: Component {
id: buttonDelegate;
Rectangle {
height: parent.height;
width: parent.itemWidth;
color: "#FFDDDD";
border.width: 1;
Text {
anchors.centerIn: parent;
text: model.text;
}
}
}
}
}
}
I just used a hidden Column to easily compute max width of Text elements, and added a little padding in the bar width to avoid unspaced text.
Guid
Updated on July 10, 2022Comments
-
Guid almost 2 years
I need to share equally the horizontal space between all "buttons" in my Row. I use this code with a Repeater.
Component { id: buttonComponent Rectangle { height: buttonRow.height width: buttonRow.width / buttonsRepeater.count color: "#FFDDDD" Text { anchors.centerIn: parent text: model.text } } } Rectangle { color: "#DDDDDD" id: buttonBar height: 30 anchors { bottom: parent.bottom left: parent.left right: parent.right } Row { id: buttonRow anchors.fill: parent Repeater { id: buttonsRepeater model: buttonsModel delegate: buttonComponent } } }
Now, I like to compute the ideal width of the Row such that all my button texts appear correctly. How can I get this ideal width?