首页 文章

QML:如何锚定照顾现有的利润

提问于
浏览
2

Windows 7下的Qt 5.10.1 . 我试图在一个定义了边距的项目中锚定一些组件 . 我的意思是,我想锚定考虑到利润 .

我的代码:

Item {
  width: parent.width
  anchors.margins: 100

  Rectangle {
    width: 50
    height: 50
    anchors.right: parent.right
  }
}

我希望Rectangle将位于右侧,但距离边缘100 px . 相反,它只是放在边缘 .

我当然可以补充一下:

anchors.rightMargin: 100

但是我必须为主要项目的每个孩子手动执行此操作 . 我想知道是否有办法锚定现有的利润 .

1 回答

  • 2

    如果我理解得很好,你的问题不是 Rectangle 的位置,而是父母 Item 的位置 .

    由于您定义了Item的 width 而不是使用显式锚,因此边距无效 .

    尝试使用锚点而不是宽度来定位项目:

    Item {
      anchors.fill: parent
      anchors.margins: 100
    
      Rectangle {
        width: 50
        height: 50
        anchors.right: parent.right
      }
    }
    

    Item 将从其父级正确定位100px, Rectangle 将定位在 Item 的边缘 .

    请注意,QML中没有“类似于CSS填充”的行为:您必须在每个子组件中明确定义它如何填充父级 .


    Edit (following your comment):

    如果在 RowColumn 内部使用,据我所知,唯一的解决方案是在每个孩子中指定 rightMargin .

    关于 padding

    QML中不存在填充(Qt Quick Controls 2 components除外):将项目声明为另一项目的子项并不意味着它在视觉上位于其父项内 . 因此,定位元素的唯一方法是在每个孩子身上使用 anchors .

    如果要在父项中模拟填充,可以将其定义为 property 并在每个子项中使用它:

    Item {
      readonly property int padding: 100
    
      width: parent.width
      height: parent.height
    
      Rectangle {
        width: 50
        height: 50
        anchors {
          right: parent.right
          margins: parent.padding
        }
      }
    }
    

    或者把孩子包裹在另一个_2816446中:

    Item {
        width: parent.width
        height: parent.height
    
        Item {
            anchors.fill: parent
            anchors.rightMargin: 100
    
            Rectangle {
                width: 50
                height: 50
                anchors.right: parent.right
            }
        }
    }
    

相关问题