Search code examples
qtqmlqt-quick

How to prevent blurry QtGraphicalEffects from being cut off?


qml window with cut-off drop shadow

I'm trying to add effects to my items using QtQuick 2 with QtGraphicalEffects, but I don't quite understand how to tweak really blurry effects to look right.

In this case, the drop shadow is poorly sized and is getting clipped at the edges before it entirely fades away. How can I make it blend in nicely and not get cut off?

This is the code for the window:

import QtQuick 2.0
import QtGraphicalEffects 1.0

Item {
    width: 250
    height: 75

    Text {
        id: textItem
        x: 10; y: 10
        text: "how can I fix my shadow?"
    }

    DropShadow {
        id: shadowEffect
        anchors.fill: textItem
        source: textItem

        radius: 8
        samples: 16

        horizontalOffset: 20
        verticalOffset: 20
    }
}

Solution

  • You must allow the original item (which will be replicated by the effect) to have enough space around it to allow the effect to be drawn completely, I would do something like this :

    import QtQuick 2.0
    import QtGraphicalEffects 1.0
    
    Item {
        width: 320;
        height: 240;
    
        Text {
            id: textItem;
            anchors.centerIn: parent;
            text: "how can I fix my shadow?";
    
            /* extend the bounding rect to make room for the shadow */
            height: paintedHeight + (shadowEffect.radius * 2);
            width: paintedWidth + (shadowEffect.radius * 2);
    
            /* center the text to have space on each side of the characters */
            horizontalAlignment: Text.AlignHCenter;
            verticalAlignment: Text.AlignVCenter;
    
            /* hide the original item because the Graphical Effect duplicates it anyway */
            visible: false;
        }
        DropShadow {
            id: shadowEffect;
            anchors.fill: source;
            source: textItem;
            radius: 8;
            samples: 16;
            horizontalOffset: 20;
            verticalOffset: 20;
        }
    }