在QML行中平均分配水平空间

时间:2013-05-16 09:46:32

标签: qt qml

我需要在我的行中所有“按钮”之间平均分配水平空间。 我将此代码与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
        }
    }
}

现在,我喜欢计算Row的理想宽度,以便我的所有按钮文本都能正确显示。 我怎样才能得到理想的宽度?

2 个答案:

答案 0 :(得分:3)

如果您不想使用QtQuick.Layouts,因为它们尚未准备就绪,您可以使用:

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;
                    }
                }
            }
        }
    }
}

我只是使用隐藏的列来轻松计算文本元素的最大宽度,并在条形宽度中添加了一点填充以避免不间隔的文本。

答案 1 :(得分:2)

按钮本身的最小宽度是其Text元素的implicitWidth属性。

您的问题的一个解决方案可能是在Component.onCompleted处理程序中添加代码,即在转发器创建其项目后执行的代码,然后总结每个转发器项目的这些implicitWidth属性(您可以通过使用其itemAt(索引)函数获得。

这种动态布局在QML中仍然有点麻烦,随着Qt Quick Layouts

的引入,Qt 5.1会更好
相关问题