【问题标题】:Qt Quick2 Custom Controls that Organize Their Children组织孩子的 Qt Quick2 自定义控件
【发布时间】:2020-09-10 20:50:01
【问题描述】:

我想实现一个自定义的 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,但目前尚不清楚这是如何完成的。或者,如果这是确保子控件进入父自定义控件布局的最合适方式。

这可能吗?

【问题讨论】:

    标签: qt qml qtquick2


    【解决方案1】:

    您只需要使用default property

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

    然后 ButtonBar 的任何子级都将插入到mainRow

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      相关资源
      最近更新 更多