QML(Qt 5):调整大小后图像左上角的叠加按钮

时间:2015-02-03 10:04:58

标签: qt qml qt5 qtquick2

我有这个代码(减少到最小):

import QtQuick 2.0
import QtQuick.Controls 1.3

Item {
    Image {
        id: img
        source: "cluster.png"
        width: 150
        height: 150
        fillMode: Image.PreserveAspectFit
   }

   Button {
        id: butn
        anchors.left: img.left
        anchors.top: img.top
        width: 20
        height: 20
        text: "Push!"
   }
}

生成类似于以下内容的图像:

Example in qmlscene

但我想将按钮放在已调整大小的图像的左上角。

完整图片位于:http://susepaste.org/34762236

这可以用QML吗?

1 个答案:

答案 0 :(得分:2)

您需要访问缩放图片的实际尺寸,以便有paintedHeight propertypaintedWidth

这会导致

Item {
    Image {
        id: img
        source: "cluster.png"
        width: 150
        height: 150
        fillMode: Image.PreserveAspectFit
    }

    Button {
        id: butn
        anchors.left: img.left
        anchors.top: img.top
        anchors.leftMargin: (img.width - img.paintedWidth)/2
        anchors.topMargin: (img.height - img.paintedHeight)/2
        width: 20
        height: 20
        text: "Push!"
    }
}

您也可以使用xy代替锚点和边距。