为什么在这种情况下创建循环?

时间:2018-11-04 17:53:10

标签: qt qml qtquickcontrols2

此示例为我提供了属性绑定错误:

file:///home/user/qmltests/layouts.qml:22:4: QML Label: Binding loop detected for property "font.pixelSize"
file:///home/user/qmltests/layouts.qml:22:4: QML Label: Binding loop detected for property "font.pixelSize"
file:///home/user/qmltests/layouts.qml:18:4: QML Label: Binding loop detected for property "font.pixelSize"

代码:

import QtQuick 2.11
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.11

Page {
    id: root
    width: 400
    height: 200
    StackLayout {
        id: main_container
        Layout.fillWidth:true
        Layout.fillHeight:true
        ColumnLayout {
            id: sub_container
            Layout.fillWidth:true
            Layout.fillHeight:true
            Label {
                text: "One"
                font.pixelSize: sub_container.height*0.2
            }
            Label {
                text: "Two"
                font.pixelSize: sub_container.height*0.2
            }
        }
    }
}

从逻辑上讲,这不应该发生,因为我正在使用widthheightLayout.fillWidth=truelayout.fillHeight=true复制到较低级别的组件中

要解决此错误,我必须从根元素复制高度:

import QtQuick 2.11
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.11

Page {
    id: root
    width: 400
    height: 200
    StackLayout {
        id: main_container
        Layout.fillWidth:true
        Layout.fillHeight:true
        ColumnLayout {
            id: sub_container
            Layout.fillWidth:true
            Layout.fillHeight:true
            Label {
                text: "One"
                font.pixelSize: root.height*0.2
            }
            Label {
                text: "Two"
                font.pixelSize: root.height*0.2
            }
        }
    }
}

为什么widthheight不能从root元素传播到子布局?

我如何引用sub_container.widthsub_container.height(因为在放置项目之前就知道了)而不会出现绑定循环错误?我不想引用根项目,因为由于复杂性,根项目中可能会有许多布局,并且为了以可扩展的方式布局组件,我需要知道父布局的宽度和高度。

1 个答案:

答案 0 :(得分:2)

如果使用布局,则它们管理的元素不得基于 在布局给定的尺寸上。要执行您想做的事情,您不应该使用布局,而是锚定,因为您要手动管理子尺寸。之所以存在循环,是因为布局使用项目的大小来调整自身大小,然后使用项目来不断地调整自身大小。如您所见,如果您不需要该功能,它将产生干扰。它通过root起作用的原因是root的大小不受布局管理:它是固定的。这就是你一直想要的,不是吗?

另一种方法是使标签不根据字体大小更改其大小提示,以使布局不会对字体大小的变化做出反应。

TL; DR:布局根据子项的大小自行调整大小,因此,如果子项根据布局的大小进行自身调整,则会出现循环。

相关问题