【问题标题】:QML Layouts: How to give weights to items in a row or column layout?QML 布局:如何为行或列布局中的项目赋予权重?
【发布时间】:2018-11-12 01:33:10
【问题描述】:

我试图通过为每个项目指定一种重量来找出按比例布局项目的方法。例如,Android 处理他们的layouts 的方式。

我试图实现它的方式是这样的:

import QtQuick 2.10
import QtQuick.Controls 2.3
import QtQuick.Layouts 1.3

GridLayout {
    columns: 4
    width: 640
    height: 480

    Rectangle {
        color: "red"
        Layout.fillHeight: true
        Layout.fillWidth: true
        Layout.columnSpan: 1
    }
    Rectangle {
        color: "#80000000"
        Layout.fillHeight: true
        Layout.fillWidth: true
        Layout.columnSpan: 2
    }
    Rectangle {
        color: "blue"
        Layout.fillHeight: true
        Layout.fillWidth: true
        Layout.columnSpan: 1
    }
}

我希望中间矩形的宽度是其他两个矩形的总和,但它们的宽度都是相等的。

在 Layout 附加属性上使用关系绑定似乎总是会导致奇怪的绑定循环。我知道我可以只使用 Row 来代替关系绑定,但如果可能的话,我更喜欢使用 Layouts。

编辑

这似乎按我想要的方式工作,但我不知道为什么会这样。它的行为就像preferredWidth 值是项目的重量一样。

import QtQuick 2.10
import QtQuick.Controls 2.3
import QtQuick.Layouts 1.3

RowLayout {
    width: 640
    height: 480

    Rectangle {
        color: "red"
        Layout.fillHeight: true
        Layout.fillWidth: true
        Layout.preferredWidth: 1
    }
    Rectangle {
        color: "#80000000"
        Layout.fillHeight: true
        Layout.fillWidth: true
        Layout.preferredWidth: 2
    }
    Rectangle {
        color: "blue"
        Layout.fillHeight: true
        Layout.fillWidth: true
        Layout.preferredWidth: 1
    }
}

【问题讨论】:

  • 这个要多加注意!如果您在相同的代码中将columnSpan 替换为rowSpan,那么它可以正常工作,即中间矩形跨越2 行.. 那么为什么columnSpan 不起作用需要一个微妙的推理,除非那只是一个错误??!!
  • 同理,如果您将布局流设置为 flow: GridLayout.TopToBottom ,则再次跨列工作

标签: qt qml qgridlayout


【解决方案1】:

不确定是否有意,但 Layout.preferredWidth(或 ColumnLayouts 的 Layout.preferredHeight)可以用作“权重”。当还指定Layout.minimumWidth 时,事情就会中断,但我认为在尝试根据权重实现布局时指定最小尺寸没有多大意义。

import QtQuick 2.10
import QtQuick.Controls 2.3
import QtQuick.Layouts 1.3

RowLayout {
    width: 640
    height: 480

    Rectangle {
        color: "red"
        Layout.fillHeight: true
        Layout.fillWidth: true
        Layout.preferredWidth: 1
    }
    Rectangle {
        color: "#80000000"
        Layout.fillHeight: true
        Layout.fillWidth: true
        Layout.preferredWidth: 2
    }
    Rectangle {
        color: "blue"
        Layout.fillHeight: true
        Layout.fillWidth: true
        Layout.preferredWidth: 1
    }
}

【讨论】:

  • 太棒了!这怎么不在Layoutdocs里?!?
猜你喜欢
  • 2015-09-29
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 2023-03-07
相关资源
最近更新 更多