【问题标题】:How to override QML item如何覆盖 QML 项目
【发布时间】:2022-06-22 22:10:31
【问题描述】:

我有一个“基础”组件,它控制项目“childItem”的纵横比:

//AspectRatio.qml

import QtQuick 2.12

Rectangle
{
  property real targetAspectRatio: 16 / 9

  color: "black"
  anchors.fill: parent

  onWidthChanged:
  {
    var _ratio = parent.width / parent.height
    var _width = 0

    if(_ratio > targetAspectRatio) //Too wide
    {
      _width = parent.height * targetAspectRatio
    }
    else
    {
      _width = parent.width
    }

    childItem.width = _width
  }

  onHeightChanged:
  {
    var _ratio = parent.width / parent.height
    var _height = 0

    if(_ratio > targetAspectRatio) //Too wide
    {
      _height = parent.height
    }
    else
    {
      _height = parent.width / targetAspectRatio
    }

    childItem.height = _height
  }

  Item
  {
    id: childItem
    anchors.centerIn: parent
  }
}

我想将 AspectRatio.qml 用作通用组件并覆盖“childItem”,具体取决于使用组件的上下文。如何像这样覆盖“childItem”?

//child.qml

AspectRatio
{
  childItem : Rectangle
  {
    color: "red"
  }
}

这种机制也用在标准的 qml 组件中,比如here。但我不清楚如何实现这一点。

【问题讨论】:

    标签: qt qml


    【解决方案1】:

    您不能“覆盖”一个项目,但您可以创建一个指向项目的子列表的属性。这就是您在控件中提到的background 属性之类的工作方式。通过分配给该属性,您实际上是在插入一个对象作为包含 Item 的任何内容的子项。

    //AspectRatio.qml
    Rectangle
    {
        property alias childItem: childContainer.data
    
        Item 
        {
            id: childContainer
            anchors.centerIn: parent
        }
    }
    
    //child.qml
    AspectRatio
    {
        childItem : Rectangle
        {
            width: 100
            height: 100
            color: "red"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 2020-03-27
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多