Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render text with QOpenGLWidget

Tags:

c++

qt

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...

like image 798
Mircea Ispas Avatar asked Jan 29 '15 13:01

Mircea Ispas


People also ask

How does text rendering work?

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).


1 Answers

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();
}
like image 99
Nils Schimmelmann Avatar answered Nov 16 '22 01:11

Nils Schimmelmann