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...
As you seem to be wanting to draw 2D text, use QPainter::drawText(). See here for info about using QPainter on a QOpenGLWidget. For using antialiasing for text rendering on QOpenGLWidgets see here.
If you want to draw 2.5D text (2D text moving with the 3D scene) it is not "too hard" to roll your own classes. Use QFont and QFontMetricsF to build a texture for your font glyphs, build some quads for each glyph into a VBO and draw the proper quads for the glyphs in a string...
QPainter::drawText on a QOpenGLWidget relies on GL_UNPACK_ALIGNMENT being set to 4, otherwise characters will look corrupt/scrambled.
If you have this problem in your application, make sure to call
before drawing the text. (see https://bugreports.qt.io/browse/QTBUG-65496 for more info)
You can implement this functionality by yourself based on the old Qt source code.
In your OpenGL widget class inherited from QOpenGLWidget (in this example it's GLBox) you have to implement the following methods:
renderText:
project:
and finally transformPoint:
If you need renderText() because you have to port your Qt4 application to Qt5 just make sure to change the signature of the function provided here to
and you don't have to worry about this anymore.
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.