在QML中,可以使用ColumnLayout或RowLayout来实现将一组小部件居中的效果。以下是一个示例代码:
import QtQuick 2.0
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
ApplicationWindow {
visible: true
width: 400
height: 300
title: "Centered Widgets"
ColumnLayout {
anchors.centerIn: parent
spacing: 10
Rectangle {
width: 100
height: 50
color: "red"
}
Rectangle {
width: 100
height: 50
color: "green"
}
Rectangle {
width: 100
height: 50
color: "blue"
}
}
}
在这个示例中,我们使用了一个ColumnLayout作为根布局,并使用anchors.centerIn: parent将它居中放置在父窗口中。在ColumnLayout中,我们添加了三个矩形小部件,它们的宽度为100,高度为50,颜色分别为红色、绿色和蓝色。这些小部件将按照垂直方向排列,并且居中对齐。
你也可以使用RowLayout来实现水平方向的居中对齐,只需要将ColumnLayout替换为RowLayout即可。