qt - qml 使用 Row 在中心对齐组件

标签 qt qml qt-quick qtquickcontrols

我正在使用 RowRectangle 上布置一些按钮这是我的自定义工具栏实现。问题是无论我做什么,组件总是从左边对齐。我希望它们与行的中心对齐并向外流向边缘。代码如下所示:

Rectangle {
        id: toolbar
        color: "green"
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        height: 100

        Row
        {
            anchors.fill: parent                
            anchors.horizontalCenter: parent.horizontalCenter
            spacing: 60

            ToolButton {
                height: parent.height
                Image {
                    anchors.verticalCenter: parent.verticalCenter
                    source: "../images/image.png"
                }
            }

            ToolButton {
                height: parent.height
                Image {
                    anchors.verticalCenter: parent.verticalCenter
                    source: "../images/image.png"
                }
            }
        }
 }

我的按钮总是从行的左侧开始布置。相反,我想让它们相对于工具栏的中心布置。我想指定这一行 anchors.horizontalCenter: parent.horizontalCenter应该实现这一点,但无论我尝试什么,组件都是从左边界布置的。

最佳答案

如果您将 Row 的对齐方式设置为父对象的中心,然后将 Row 的宽度调整为 childrenRect 的宽度,那么您可以让项目从对象的中心展开。注意:您可能需要设置 ToolButton 的宽度,以便 childrenRect 填充其宽度值。

   Rectangle {
        id: toolbar
        color: "green"
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        height: 100

        Row
        {
            anchors{
                horizontalCenter: parent.horizontalCenter
                verticalCenter: parent.verticalCenter
            }
            height: parent.height
            width: childrenRect.width
            spacing: 60

            ToolButton {
                height: parent.height
                width: 50
                Image {
                    anchors.verticalCenter: parent.verticalCenter
                    source: "../images/image.png"
                }
            }

            ToolButton {
                height: parent.height
                width: 50
                Image {
                    anchors.verticalCenter: parent.verticalCenter
                    source: "../images/image.png"
                }
            }
        }
 }

关于qt - qml 使用 Row 在中心对齐组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47055333/

相关文章:

qt - PyQt 5.7 中 GraphicsView 中的奇怪绘画错误

qt - 静态编译 Qt 4.6.2

c++ - 如何使用 CMake 项目调试 QML

qt - 如何从 C++ 对 Qt Quick TextEdit 对象运行命令?

QtQuickControls2对话框在点击外部时消失

qt - 将 Qt GUI 嵌入到现有的 OpenGL 程序中

qt - 如何在单独的文件中定义 js 函数并将其附加到 QML 元素

c++ - 将二维数组整数数据从 C++ 发送到 qml

qt - QML 是否支持属性的私有(private)访问说明符?

qt - 如何在 Android 平板电脑上实现主从 View Qt/QML?