组织子项的 Qt Quick2 自定义控件

Qt Quick2 Custom Controls that Organize Their Children

我想实现一个自定义的 Qt5 Quick 2 QML 自定义控件,它将一组任意和不同的按钮组合成一行,没有间距,给它一个边距,然后在它们周围画一个小边框(稍后,也许是阴影或其他效果)。

我希望使用起来非常简单,而不是需要大量的支持结构,但我现在不知道如何正确定义一个控件,而不是包含其他控件并组织它们。

我可以创建一个自定义矩形,然后将 RowLayout 锚定到其内部,

BubbleButtonBar
{
    RowLayout
    {
       Button
       {
           text:"First"
       }
       Button
       {
           text:"Second"
       }
       Button
       {
           text:"Third"
       }
    }
}

但我希望让它更自动化,看起来像这样:

ButtonBar
{
   Button
   {
       text:"First"
   }
   Button
   {
       text:"Second"
   }
   Button
   {
       text:"Third"
   }
}

但是,我不知道如何让 ButtonBar.qml 文件将其子控件插入给定位置:

import QtQuick 2.0
import QtQuick.Layouts 1.15
import QtQuick.Controls 2.15

Item {
    
    property int pad: 50
    property int borderSize: 2
    width:mainRow.width + pad
    height: mainRow.height + pad

    Rectangle
    {
        x: pad/2 - borderSize
        y: pad/2 - borderSize
        width:mainRow.width + borderSize*2
        height: mainRow.height + borderSize*2

        border.width: borderSize
        border.color: "red"

        RowLayout
        {
            id: mainRow
            spacing: 0
            x: borderSize
            y: borderSize
            // <------- How to get child controls to insert here?           
        }
    }
}

似乎自定义 container control 可能允许我定义 contentItem,但尚不清楚这是如何完成的。或者,如果这是最合适的方式,请确保子控件找到进入父自定义控件布局的方式。

这可能吗?

你只需要使用一个default property

// ButtonBar.qml
Item {
    default property alias contents: mainRow.data

    RowLayout {
        id: mainRow
    }
}

然后 ButtonBar 的所有子项都将插入 mainRow