In older version of Qt there was QGLWidget, with a nice function called renderText. Now I'm using QOpenGLWidget class and the functionality for rendering text is missing.
Is there a easy way to render text using QOpenGLWidget? I won't like to build the whole text rendering with OpenGL from scratch...
The process of transforming font outlines into pixels is called rasterization. The operating system's text-rendering engine places the outline (ie the shape) of each character at the desired font size on a pixel grid. Next, it colours all the pixels whose centre is inside the outline (see image below).
I ended up doing a solution similar to what @jaba wrote. I also noticed some graphical corruption unless I called painter.end() at the end of the method.
void MapCanvas::renderText(double x, double y, double z, const QString &str, const QFont & font = QFont()) {
// Identify x and y locations to render text within widget
int height = this->height();
GLdouble textPosX = 0, textPosY = 0, textPosZ = 0;
project(x, y, 0f, &textPosX, &textPosY, &textPosZ);
textPosY = height - textPosY; // y is inverted
// Retrieve last OpenGL color to use as a font color
GLdouble glColor[4];
glGetDoublev(GL_CURRENT_COLOR, glColor);
QColor fontColor = QColor(glColor[0], glColor[1], glColor[2], glColor[3]);
// Render text
QPainter painter(this);
painter.setPen(fontColor);
painter.setFont(font);
painter.drawText(textPosX, textPosY, text);
painter.end();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With