Pillar
Pillar

Reputation: 107

Transparent button text over the background

I am trying to make transparent text in qml. I have a customized button:

ApplicationWindow {
    visible: true
    width: 320
    height:240
    style: ApplicationWindowStyle {
            background: Image { // paste any url here
                source: "https://t4.ftcdn.net/jpg/01/05/18/57/240_F_105185755_w384KDBvemK5Mn4oXzrWbCz9SRvHuDIh.jpg"
            }
    }
    Button
    {
        anchors.centerIn: parent
        style: ButtonStyle
        {
            padding
            {
                left: 16
                right: 16
                top: 8
                bottom: 8
            }

            background:
                Rectangle
                {
                    antialiasing: true
                    color: control.pressed ? "#d1d1d1" : control.hovered ? "#666" : "transparent"
                    border.color: "white"
                    radius: height/2
                    border.width: 1
                }

            label:
                Text
                {
                    text: "buttonText"
                    color: control.pressed ? "white" : control.hovered ? "#00000000" : "white"
                }
            }
        }
    }

All I want is to have transparent text in button in hovered state. Text should have the color of background. Example: Example

upd. I need this to work without shaders on slow pc.

Upvotes: 0

Views: 1237

Answers (1)

Kevin Krammer
Kevin Krammer

Reputation: 5207

One option would be to use a custom QQuickPaintedItem and use a QPainterPath to draw the "text shaped hole".

Basically like this

void MyItem::paint(QPainter *painter)
{
    QPainterPath path;
    path.addRect(0, 0, width(), height());
    path.addText(textX, textY, font, yourText);

    painter->setBrush(yourBackgroundColor);
    painter->setPen(Qt::transparent);
    painter->drawPath(path);
}

The position, i.e. textX and textY, would have to be calculated manually I am afraid, though QFontMetrics::boundingRect() should help there.

Upvotes: 1

Related Questions