Drawing Text Captions on Images in Qt for Python: Qt Image Viewer Part 3
We have image transformations, now we look at Captions.
Why draw text? Well, we need captions when illustrating a point, to create watermarks, and when creating memes.
To expand the requirement, we need:
- Colors
- Lines
- Boxes
- Transparency
- Fonts
Fonts
We will start with the font, we are drawing text after all, but which fonts are available? Remember, this is the fonts installed at the destination server, not your dev machine ...
# Which fonts are available?
db = QFontDatabase()
for font in db.families():
print(font)
Choose your font thusly:
font = QFont("Ubuntu Condensed", 50)
Now you know the font families, we can choose our color (or colour in actual English ;) )
Color
There are three ways to pic your color, go with what works for you:
color = QColor(80, 80, 80)
color = QColor("#0000AA")
color = QColor("White")
Once you have a color, now you can set the alpha (transparency):
color.setAlpha(100)
Drawing
To draw we take our existing picture as a background, then set up a painter and a pen:
painter = QPainter(picture)
painter.setPen(QPen(QColor(80, 80, 80), 5, QtCore.Qt.DashDotLine, QtCore.Qt.RoundCap))
If you want a filled shape then you will need a brush
color = QColor("#0000AA")
color.setAlpha(100)
brush = QBrush(color)
Note we can also set the line width and style of that line.
Once we are set up we can draw our lines, boxes, and text:
painter.drawLine(25, 105, 200, 105)
painter.drawRect(0, 0, 220, 125)
painter.drawText(20, 100, "Hello!")
Finish up with saving the changes:
painter.save()
painter.end()