我正在尝试编写简单的 QML 应用程序,它将由许多重复的元素组成,按行组织。结果将类似于下面的结果:
目前,我有一段重复的代码可以实现这个目标:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Controls.Material 2.3
import QtQuick.Layouts 1.12
ApplicationWindow {
Material.theme: Material.Dark
visible: true
width: 480
height: 640
title: qsTr("Hello world!")
id: root
GridLayout {
anchors.horizontalCenter: parent.horizontalCenter
columns: 3
Text {
color: "white"
text: "aaa"
font.family: "Ubuntu"
font.pixelSize: 20
}
SpinBox {
from: 0
to: 1000
stepSize: 1
editable: true
}
Rectangle {
width: 40
height: 20
color: "#F48FB1"
Text {
font.family: "Ubuntu"
font.pixelSize: 16
text: "ml"
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
}
}
Text {
color: "white"
text: "bbb"
font.family: "Ubuntu"
font.pixelSize: 20
}
SpinBox {
from: 0
to: 100
stepSize: 1
editable: true
}
Rectangle {
width: 40
height: 20
color: "#F48FB1"
Text {
font.family: "Ubuntu"
font.pixelSize: 16
text: "%"
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
}
}
Text {
color: "white"
text: "ccc"
font.family: "Ubuntu"
font.pixelSize: 20
}
SpinBox {
from: 0
to: 100
stepSize: 1
editable: true
}
Rectangle {
width: 40
height: 20
color: "#F48FB1"
Text {
font.family: "Ubuntu"
font.pixelSize: 16
text: "%"
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
}
}
}
}
但是,每一行都有完全相同的结构,所以我尝试从代码中提取组件:
Item {
id: ingredient
property alias ingredientText: qualifier.text
property alias ingredientMaxValue: amount.to
property alias ingredientUnit: unit.text
RowLayout {
Text {
id: qualifier
color: "white"
text: "asdf"
font.family: "Ubuntu"
font.pixelSize: 20
}
SpinBox {
id: amount
from: 0
to: 1000
stepSize: 1
editable: true
}
Rectangle {
width: 40
height: 20
color: "#F48FB1"
Text {
id: unit
font.family: "Ubuntu"
font.pixelSize: 16
text: "unit"
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
}
}
}
}
不幸的是,当我尝试在主窗口中使用我的组件时,它未对齐并超出了它的可见部分(最大化窗口后我可以再次看到它):
ApplicationWindow {
Material.theme: Material.Dark
visible: true
width: 480
height: 640
title: qsTr("Hello world!")
id: root
GridLayout { // I know now it will not work properly for sure,
// but i tried using other layouts and alignment methods
// and it didn't help me at all
anchors.horizontalCenter: parent.horizontalCenter
columns: 3
Ingredient {
ingredientMaxValue: 100; ingredientText: "qwerty"; ingredientUnit: "kg"
}
}
}
问题是:如何使用“成分”组件实现第一张图片中的项目对齐?