How to use QPainter in QOpenGlWidget paintGL

I recently switched from QGLWidget to the new QOpenGlWidget, because in a later version there is no renderText () function. I am thinking of using QPainter to draw text on top of my openGL 3D graphics.

I initially displayed everything through the paintGL () function, how can I safely add to QPainter in this function?

My code looks like this:

paintGL()
{
    //Raw OpenGL codes
    //....

    //Where to safely use the QPainter?
}
+4
source share
1 answer

Just add the QPaintercalls directly to the method paintGL().

paintGL()
{
    // OpenGL code...

    QPainter p(this);
    p.drawText(...);

}

The function paintGL()is called QOpenGLWidget::paintEvent(), so QPainterthere should be no problems with use .

A small example:

class CMyTestOpenGLWidget : public QOpenGLWidget
{
public:
    CMyTestOpenGLWidget(QWidget* parent) : QOpenGLWidget(parent) {}

    void initializeGL() override
    {
        glClearColor(0, 0, 0, 1);
        glEnable(GL_DEPTH_TEST);
        glEnable(GL_LIGHT0);
        glEnable(GL_LIGHTING);
        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
        glEnable(GL_COLOR_MATERIAL);
    }

    void paintGL() override
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glBegin(GL_TRIANGLES);
        glColor3f(1.0, 0.0, 0.0);
        glVertex3f(-0.5, -0.5, 0);
        glColor3f(0.0, 1.0, 0.0);
        glVertex3f(0.5, -0.5, 0);
        glColor3f(0.0, 0.0, 1.0);
        glVertex3f(0.0, 0.5, 0);
        glEnd();

        QPainter p(this);
        p.setPen(Qt::red);
        p.drawLine(rect().topLeft(), rect().bottomRight()); 
    }

    void resizeGL(int w, int h) override
    {
        glViewport(0, 0, w, h);
    }
};

enter image description here

+2
source

All Articles