0

I'm new to ui design and was wondering how I could achieve an effect where some font-based text on top of a layer is drawn as being "cut-out" from said layer, if that's even possible.

concept

Basically akin to the example below Ideally something where the layer the text is "cut out" from can itself have effects, such as semi-transparency and/or blur, where the effect would still work if said layer has a translation across the background.

example

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
memeko
  • 163
  • 1
  • 7

1 Answers1

4

You can do that with a QPainterPath and a QPainter.

Use QPainterPath to define the white part on your image. First, create a path with a rect (rounded rect). Then, add your text with the right font to the path. By default, the fill rule will remove the text from the rect.

Use QPainter to draw the path on your background image. Don't forget to enable antialiasing for a better render.

An example:

class Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        label = QLabel(self)
        label.setPixmap(self.makePixmap("knockout"))

    def makePixmap(self, text):
        background = QPixmap(600, 80)
        background.fill(Qt.red)      # Your background image

        textMask = QPainterPath() 
        textMask.addRect(75, 20, 300, 40) # The white part
        textMask.addText(QPoint(90, 50), QFont("Helvetica [Cronyx]", 24), text) # the path will substract the text to the rect

        painter = QPainter(background)
        painter.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing)

        painter.fillPath(textMask, QBrush(Qt.white)) # Will draw the white part with the text "cut out"

        painter.end()
        return background
Dimitry Ernot
  • 6,256
  • 2
  • 25
  • 37