qt - 更改 GridLayout 内项目的宽度
问题描述
我正在qml中设计一个简单的高分。我决定在 GroupBox 中使用 GridLayout 来显示一些文本。我不知道为什么,但我无法更改文本的宽度。我已经尝试过利润,但它们也不起作用。现在文本崩溃到 GroupBox 的边框。(我想在 Item 中使用 GroupBox,因为稍后我将在其中添加其他内容,例如按钮。)
Item {
id: highscores
width: 450
GroupBox {
id: highscore_box
title: qsTr("GroupBox")
anchors.centerIn: parent
width: parent.width
height: 450
background: Rectangle {
y: highscore_box.topPadding - highscore_box.padding
width: parent.width
height: parent.height - highscore_box.topPadding + highscore_box.padding
color: "transparent"
border.color: "white"
border.width: 5
radius: 10
}
label: Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.top
anchors.bottomMargin: -height/2
color: "white" //set this to the background color
width: parent.width * 0.6
height: box_title.font.pixelSize
Text {
id: box_title
text: qsTr("High Scores")
anchors.centerIn: parent
font.pixelSize: 32
font.family: "Super Mario Bros."
}
}
contentItem: GridLayout {
id: highscore_grid
columns: 3
//width: ?????
Text {text: "Place";font.bold: true; color: "white";
font.family: "Super Mario Bros."; font.pixelSize: 30}
Text {text: "Player";font.bold: true; color: "white";
font.family: "Super Mario Bros."; font.pixelSize: 30}
Text {text: "Time";font.bold: true; color: "white";
font.family: "Super Mario Bros."; font.pixelSize: 30}
Text {text: "1st";font.bold: true; color: "white";
font.family: "Super Mario Bros."; font.pixelSize: 20}
Text {text: "--";font.bold: true; color: "white";
font.family: "Super Mario Bros."; font.pixelSize: 20}
Text {text: "--";font.bold: true; color: "white";
font.family: "Super Mario Bros."; font.pixelSize: 20}
}
}
}
解决方案
使用布局时,您不能使用标准的锚点调用。您将需要使用以下这些调用来操作您的网格布局。
此外,当你声明一个布局时,你需要指定它将占据什么空间。你可以使用类似的东西
anchors.fill: parent
之后,您可能还需要指定网格布局内的对象将占用的空间。再一次,不要使用标准的 width/len 调用,而是使用 Layout.XXXX 调用。
布局非常适合构建流畅和动态的屏幕,但有时它们可能是小流氓。嵌套布局非常有益。我个人使用多层深度布局。格!
我建议创建一个“练习”QML 文件,您可以在其中创建一个包含许多对象的网格布局。矩形/按钮/更多布局。适应它。一旦您对布局有了更多了解,然后尝试将其应用于涉及 MVC 的现有问题。