如何在QML中更新基于加载器的底部控件

How update bottom control based on loader in QML

本文关键字:加载 控件 底部 于加载 QML 更新      更新时间:2023-10-16

我有一个主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"
        }
    }
}

问题:

底部项与中间项重叠

你的代码有两个问题:

  1. 你应该给下面的
  2. 设置一个高度和宽度
  3. 你应该给你的新高度和宽度。/ol>

    试试这个:

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