0

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.

Community
  • 1
  • 1
Pillar
  • 87
  • 2
  • 11
  • 2
    Can [this post](http://stackoverflow.com/questions/39903639/how-to-apply-opacity-mask-to-a-qml-item) help you? – lolo Oct 10 '16 at 14:04
  • @user2436719 I need this example to work on a slow pc with old integrated video card and my program would have lots of buttons. Is there any ability to do it without shaders? – Pillar Oct 10 '16 at 14:26
  • 2
    @Pillar - everything in OpenGL already uses shaders. The shader itself is trivial, barely slower than flat color shading. And NO, you can't do anything in OpenGL without using shaders. And QML uses OpenGL. One way or the other, you will end up using shaders. – dtech Oct 10 '16 at 14:29
  • 1
    TL;DR: If you're using Qt Quick, you're using shaders already. Shaders make it faster on slow PCs, since they are specialized to do that sort of repetitive processing **very quickly** - at least an order of magnitude faster than the CPU can do it. – Kuba hasn't forgotten Monica Oct 10 '16 at 16:27

1 Answers1

1

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.

Kevin Krammer
  • 5,159
  • 2
  • 9
  • 22