【问题标题】:Applying mask to image breaks alignment将蒙版应用于图像会中断对齐
【发布时间】:2017-10-07 21:21:52
【问题描述】:

每当我对图像应用蒙版以使其成为圆形时,UI 元素的对齐方式就会中断。图像向右偏移了一些像素。

// main.qml
import QtQuick 2.8
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.1

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Example")

    Page1Form {

    }
}

// Page1Form.qml
import QtQuick 2.8
import QtQuick.Layouts 1.1
import QtQuick.Controls 2.1

Item {
   RowLayout {
        id: playerRowLayout

        Layout.alignment: Qt.AlignLeft

        Layout.fillWidth: true

        RoundedImage {
            id: displayImage

            width: 50
            height: 50

            Layout.preferredWidth: 50
            Layout.preferredHeight: 50

            source: "Images/DisplayPicture.jpeg"

            sourceSize.width: width
            sourceSize.height: height
        }

        Text {
            id: playerText
            text: qsTr("Hameer Abbasi (Pro)")
            font.family: "Source Sans Pro"
            font.pixelSize: 12
        }
    }
}

// RoundedImage.qml
import QtQuick 2.8
import QtGraphicalEffects 1.0

Image {
    id: img
    property bool rounded: true
    property bool adapt: true

    layer.enabled: rounded
    layer.effect: OpacityMask {
        maskSource: Rectangle {
            anchors.centerIn: parent
            width: adapt ? img.width : Math.min(img.width, img.height)
            height: adapt ? img.height : Math.min(img.width, img.height)
            radius: Math.min(width, height)*0.5
        }
    }
}

当我将 RoundedImage 更改为 Image 时,错位消失了,如下所示:

另外,当我将anchors.fill: imganchors.centerIn: img 添加到OpacityMask 时,我得到以下结果(如您所见,错位并没有消失,而是移动了):

唯一起作用的似乎是在文本框上设置anchors.right: displayImage.left,但不知何故这似乎是一种黑客行为,我觉得我做的事情不正确。有人可以帮我找出问题出在哪里以及解决此问题的“正确”方法是什么?

【问题讨论】:

  • 我认为你不应该同时使用widthLayout.preferredWidth(各自的高度)。考虑设置效果的sourceRect
  • derM 添加layer.sourceRect: img.childrenRect 没有解决问题。我不确定这是否是您想要的。
  • 类似的东西。只是有时间自己尝试一下。这确实很神秘...我不知道 - 你可以放弃布局的东西并转而使用锚定和正常的Rows 吗?

标签: qt layout alignment qml


【解决方案1】:

我无法向你解释为什么这件事会发生。对我来说,它看起来像一个错误。

似乎有一个简单的解决方法:不要将Image 直接放在Layout 中。将RoundedImage.qml 更改为:

// RoundedImage.qml
import QtQuick 2.7
import QtGraphicalEffects 1.0

Item {
    id: img
    property bool rounded: true
    property bool adapt: true
    property alias source: image.source
    property alias sourceSize: image.sourceSize
    Image {
        id: image

        width: img.width
        height: img.height
        layer.enabled: rounded
        layer.effect: OpacityMask {
            maskSource: Rectangle {
                width: adapt ? img.width : Math.min(img.width, img.height)
                height: adapt ? img.height : Math.min(img.width, img.height)
                radius: Math.min(width, height)*0.5
            }
        }
    }
}

奇怪的行为消失了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-07
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多