【问题标题】:QML: set width based on left/right anchors of other ItemsQML:根据其他项目的左/右锚设置宽度
【发布时间】:2018-04-04 20:26:42
【问题描述】:

如何根据其他项目的 anchors.left 和 anchors.right 的值设置 QML 项目的宽度?这是我想做的一个例子:

Rectangle {
    width: 400
    height: 400

    Rectangle {
        width: parent.right - parent.left
        height: parent.height
    }

}

显然,这只是一个简单的示例,因为我可以只使用width: parent.width,但这通常不起作用。例如,如果两个锚点位于不同的项目上:

Rectangle {
    width: 400
    height: 400

    Rectangle {
        anchors.left: parent.left
        width: other.left - parent.left
        height: parent.height
    }

    Rectangle {
        id: other
        anchors.right: parent.right
        width: 123
        height: parent.height
    }

}

【问题讨论】:

  • 为什么不通用?请说明具体情况。
  • 可以解释为什么最后一个例子不起作用
  • 我觉得是因为left和right的值不是整数,所以不能使用算术运算符。
  • 我最初的问题是你为什么不使用width: parent.width
  • 谢谢,这行问题让我意识到我可以使用其他项目的widths,结合它们的x值来计算它们的leftright 锚点。

标签: qt user-interface qml


【解决方案1】:

我找到了一个解决方案,虽然它有点乱。对于以下不起作用的代码:

Rectangle {
    width: 400
    height: 400

    Rectangle {
        id: other1
        anchors.left: parent.left
        width: 43 
        height: parent.height
    }

    Rectangle {
        anchors.left: other1.right 
        width: other2.left - other1.right
        height: parent.height
    }

    Rectangle {
        id: other2
        anchors.right: parent.right
        width: 123
        height: parent.height
    }

} 

other1.right 替换为other1.x + other1.width,将other2.left 替换为other2.x,得到:

Rectangle {
    width: 400
    height: 400

    Rectangle {
        id: other1
        anchors.left: parent.left
        width: 43 
        height: parent.height
    }

    Rectangle {
        anchors.left: other1.right 
        width: other2.x - (other1.x + other1.width)
        height: parent.height
    }

    Rectangle {
        id: other2
        anchors.right: parent.right
        width: 123
        height: parent.height
    }

}

【讨论】:

    【解决方案2】:

    你给一个简单的问题增加了不必要的复杂性。

    只要您想将 item 锚定到其兄弟姐妹或直接父级,您就不需要手动计算 item 的宽度。

    Positioning with Anchors

    只需锚定左侧右侧值:

    Rectangle {
        width: 400
        height: 400
    
        Rectangle {
            id: other1
            anchors.left: parent.left
            width: 43 
            height: parent.height
        }
    
        Rectangle {
            anchors.left: other1.right 
            anchors.right: other2.left
            // width: other2.x - (other1.x + other1.width) // absolutely not necessary
            height: parent.height
        }
    
        Rectangle {
            id: other2
            anchors.right: parent.right
            width: 123
            height: parent.height
        }
    
    }
    

    【讨论】:

    • 感谢您的回复。我知道如何使用 anchors.left/right,但它不适用于我的目的。我提供的示例已大大简化,但我正在尝试设置 Row 中的项目的宽度,但 Rows 不允许其子项设置锚点。
    猜你喜欢
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多