问题描述
我从事一个 Qt 项目,其中几乎所有 QML 项目都在同一个文件 main.qml
中。
该应用程序使用 StackLayout 来浏览其他 QML 文件,此外还需要在 main.qml
本身中显示项目。
我使用 Loader 调用包含 GridLayout 的组件,其中包含标签和图像。在此容器之外,还有其他图像和标签锚定在 mainWindow
的底部。
问题是,在使用Loader调用StackLayout内的Component时,Component的尺寸覆盖了applicationwindow中定义的Image。它表现为所有窗口的填充高度,这不是我想要的。
问题是,如何在不填满整个窗口的情况下加载组件,但在使用 StackLayout 之前保持原来的大小。
我仍然是 Qt 的初学者,所以欢迎任何其他首选的建议方法。
代码结构类似,
applicationwindow {
id: mainWindow
width: 500
height: 400
(... some code ...)
Image{
anchors.bottom: parent.bottom
anchors.left: parent.left
anchors.bottomMargin: 22
anchors.leftMargin: 24
width: 80
height: 40
fillMode: Image.Stretch
source: "qrc:/image.png"
}
StackLayout {
id: mainStackLayout
width: mainWindow.width
height: mainWindow.height
FirstPage {} // another .qml file
Loader {
sourceComponent: component
}
}
Component{
id: component
GridLayout {
id: grid
width: mainWindow.width
height: mainWindow.height
columns: 4
Labels{}
...
...
...
Labels{}
}
解决方法
问题主要在于您已将 StackLayout 设置为覆盖整个窗口:
width: mainWindow.width
height: mainWindow.height
并且 StackLayout 将使其子项增长以适应其大小。
两个简单的选项:
- 将您的加载器放在一个项目内,这样项目就会增长,并且您加载的组件的大小不受影响。
- 在 ApplicationWindow 上放置一个布局,以便更好地管理您的 Image 和 StackLayout。
我推荐选项 2。除非您不打算允许用户调整窗口大小,否则所有 QML 组件都应设计为可调整大小。