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