2017-05-09 60 views
0

每當我將遮罩應用於圖像以使其成爲圓形時,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 
     } 
    } 
} 

Misaligned

當我改變RoundedImageImage,錯位消失了,就像這樣:

Image no longer rounded

而且,當我添加anchors.fill: imganchors.centerIn: imgOpacityMask,我得到的以下結果(正如你所看到的,錯位沒有消失,只是移動了):

Blank space in the wrong position

確實似乎工作是設置在文本框中anchors.right: displayImage.left,但是,不知怎的,似乎是一個黑客,我覺得我沒有做正確的事情不知怎麼的唯一的事情。有人能幫我弄清楚問題出在哪裏以及解決這個問題的「正確」方法是什麼?

+0

我認爲你不應該使用'width'和'Layout.preferredWidth'(相應的高度)在一起。考慮設置效果的['sourceRect'](http://doc.qt.io/qt-5/qml-qtquick-item.html#layer.sourceRect-prop)。 – derM

+0

derM添加'layer.sourceRect:img.childrenRect'沒有解決問題。我不確定那是否是你想要的。 –

+0

就是這樣的。剛剛找到時間親自嘗試一下。這確實是神祕的......我不知道 - 你可以放棄佈局東西,然後選擇錨定和普通的「行」嗎? – derM

回答

0

我無法向你解釋爲什麼這件事情正在發生。對我來說,它看起來像一個錯誤。

看似有一個簡單的解決方法:在Layout內部沒有Image。將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 
      } 
     } 
    } 
} 

並且奇怪的行爲消失了。