如何让 Loader 不再填充其父级?
How do I get a Loader to no longer fill its parent?
我的主 QML 文件中有一个 Loader 对象。我根据当前上下文在 运行 时间在加载程序中加载不同的 QML 源。
我的步骤是这样的:
- 加载
login.qml
文件并在加载器上设置 anchors.centerIn: parent
。
- 登录成功后,加载
task.qml
,然后在加载器上设置anchors.fill: parent
。
- 用户退出后,我想重定向回
login.qml
,我在加载器上重新设置了anchors.centerIn: parent
。
我预计这会导致加载程序在父项中居中并且不再填充它。然而,这种情况并非如此。 Loader 仍然填充父级。
如何更改项目上的锚点以使其再次居中并且不再填充其父项?
您不需要再次设置anchors.centerIn
。相反,您需要将 anchors.fill
和 width
以及 height
设置为 undefined
以便它默认为隐式大小并再次使用 anchors.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
文件的顶层添加一个额外的项目,以便登录视图以该项目为中心。这将消除更改加载程序上的锚点的必要性。
我的主 QML 文件中有一个 Loader 对象。我根据当前上下文在 运行 时间在加载程序中加载不同的 QML 源。
我的步骤是这样的:
- 加载
login.qml
文件并在加载器上设置anchors.centerIn: parent
。 - 登录成功后,加载
task.qml
,然后在加载器上设置anchors.fill: parent
。 - 用户退出后,我想重定向回
login.qml
,我在加载器上重新设置了anchors.centerIn: parent
。
我预计这会导致加载程序在父项中居中并且不再填充它。然而,这种情况并非如此。 Loader 仍然填充父级。
如何更改项目上的锚点以使其再次居中并且不再填充其父项?
您不需要再次设置anchors.centerIn
。相反,您需要将 anchors.fill
和 width
以及 height
设置为 undefined
以便它默认为隐式大小并再次使用 anchors.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
文件的顶层添加一个额外的项目,以便登录视图以该项目为中心。这将消除更改加载程序上的锚点的必要性。