具有居中内容的流布局 [英] Flow layout with centered content

查看:47
本文介绍了具有居中内容的流布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当窗口宽度太小而无法显示一行中的所有项目时,我有一排项目应该堆叠起来,如下面的草图所示:

I have a row with items which should stack when the window width gets too small for displaying all items in a row, as shown in the following sketch:

Flow 组件堆叠项目,但它们不是居中而是在左侧或右侧对齐:

The Flow component stacks the items but they are not centered but aligned on the left or right side:

Flow {
    Item {}
    Item {}
    Item {}
    Item {}
    Item {}
}

QML 中是否有内置的方法来使流程居中?

Is there a built-in way in QML to make the flow centered?

推荐答案

好吧,没有内置的方法,但我找到了一种解决方法.

Well there is no built-in way but I found a workaround to do it.

这个想法很简单,因为Flow 已经是一个 Item 它有 anchors.leftMarginanchors.rightMargin.因此,如果我们可以计算出Flow 的行内有多少个元素,那么我们就可以计算出左右边距.所以我们可以居中.

The idea is simple, since Flow is already an Item it has anchors.leftMargin and anchors.rightMargin. So if we can calculate, how many elements is inside the row of theFlow then we are able to calculate the left and right margins. So we can center in.

这是一个简单的代码,

        Flow {
        property int rowCount: parent.width / (elements.itemAt(0).width + spacing)
        property int rowWidth: rowCount * elements.itemAt(0).width + (rowCount - 1) * spacing
        property int mar: (parent.width - rowWidth) / 2

        anchors {
            fill: parent
            leftMargin: mar
            rightMargin: mar
        }

        spacing: 6
        Repeater {
            id: elements
            model: 5
            Rectangle {
                color: "#aa6666"
                width: 100; height: 100
            }
        }

这篇关于具有居中内容的流布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆