Qt 如何使装入器不再填充其父级?

Qt 如何使装入器不再填充其父级?,qt,qml,qtquick2,Qt,Qml,Qtquick2,我的主QML文件中有一个Loader对象。我在运行时根据当前上下文在加载程序中加载不同的QML源 我的步骤如下: 加载login.qml文件,并在加载程序上设置anchors.centerIn:parent 成功登录后,我加载task.qml,然后在加载程序上设置anchors.fill:parent 用户注销后,我想重定向回login.qml,然后在加载程序上再次设置anchors.centerIn:parent 我希望这会导致加载程序在父对象中居中,而不再填充它。然而,情况并非如此。加载程序

我的主QML文件中有一个Loader对象。我在运行时根据当前上下文在加载程序中加载不同的QML源

我的步骤如下:

  • 加载
    login.qml
    文件,并在加载程序上设置
    anchors.centerIn:parent
  • 成功登录后,我加载
    task.qml
    ,然后在加载程序上设置
    anchors.fill:parent
  • 用户注销后,我想重定向回
    login.qml
    ,然后在加载程序上再次设置
    anchors.centerIn:parent
  • 我希望这会导致加载程序在父对象中居中,而不再填充它。然而,情况并非如此。加载程序仍然填充父级


    如何更改项目上的锚定,使其再次居中且不再填充其父项?

    您无需再次设置
    锚定。centerIn
    。相反,您需要将
    锚定.fill
    width
    height
    设置为
    undefined
    ,使其默认为隐式大小,并再次使用
    锚定.centerIn
    属性

    下面是一个工作示例:

    import QtQuick 2.0
    import QtQuick.Controls 1.0
    
    Item {
        width: 800
        height: 600
    
        Rectangle {
            id: rect
            anchors.centerIn: parent
    
            implicitWidth: 500
            implicitHeight: 200
            color: "red"
    
            Button {
                text: "Toggle Full Size"
                anchors.centerIn: parent
                onClicked: {
                    if (rect.anchors.fill) {
                        rect.anchors.fill = undefined
                        rect.width = undefined
                        rect.height = undefined
                    } else {
                        rect.anchors.fill = rect.parent
                    }
                }
            }
        }
    }
    
    或者,一个更简单的解决方案可能是让加载程序始终填充其父级,而是在
    login.qml
    文件的顶层添加一个额外的项,以便登录视图位于该项的中心。这样就不需要更换装载机上的锚