首页 文章

QML:根据其他项目的左/右锚点设置宽度

提问于
浏览
0

如何根据其他项'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
    }

}

2 回答

  • 0

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

    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
        }
    
    }
    
  • 0

    您正在为一个简单问题添加不必要的复杂性 .

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

    Positioning with Anchors .

    只需锚定左侧 and 右侧值:

    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
        }
    
    }
    

相关问题