QML中如何基于loader更新底部控件

How update bottom control based on loader in QML

我有一个主 qml 文件,其中顶部项目是一个矩形,中间项目是加载不同 qml 文件的加载器,底部项目是一些文本。

基于加载器项目,我希望底部项目应该调整,我尝试使用锚点,但有些它不起作用,有人可以解释我如何做到这一点。

这是我的代码:

main.qml

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Rectangle{
        anchors.fill: parent
        Rectangle{
            id: toprect
            width: 100
            height: 100
            color: "green"
            anchors.horizontalCenter: parent.horizontalCenter
        }
        Loader{
            id: middlerect
            anchors.top: toprect.bottom
            source: "qrc:/new.qml"
        }
        Rectangle{
            id: belowrect
            anchors.top: middlerect.bottom
            Text{
                text: "Bottom"
            }
        }
    }
}

new.qml

import QtQuick 2.0
import QtQuick.Controls 1.2

Item {
    id: newid
    Column{
        spacing: 10
        Rectangle{
            width: 100
            height: 50
            color: "lightblue"
        }
        Rectangle{
            width: 100
            height: 50
            color: "lightgreen"
        }
    }
}

问题:

底部项目与中间项目重叠

您的代码有 2 个问题:

  1. 你应该给下面的矩形一个高度和宽度
  2. 你应该给你的 new.qml 对象一个高度和宽度

试试这个:

main.qml

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Rectangle{
        anchors.fill: parent
        Rectangle{
            id: toprect
            width: 100
            height: 100
            color: "green"
            anchors.horizontalCenter: parent.horizontalCenter
        }


        Loader{
            id: middlerect
            anchors.top: toprect.bottom
            source: "qrc:/new.qml"
        }
        Rectangle{
            id: belowrect
            color:"yellow"

            width: childrenRect.width
            height: childrenRect.height
            anchors.top: middlerect.bottom
            Text{
                id:text
                text: "Bottom"
            }
        }
    }
}

new.qml

import QtQuick 2.0
import QtQuick.Controls 1.2

Item {
    id: newid
    width: childrenRect.width
    height: childrenRect.height
    Column{
        spacing: 10
        Rectangle{
            width: 100
            height: 50
            color: "lightblue"
        }
        Rectangle{
            width: 100
            height: 50
            color: "lightgreen"
        }
    }
}