Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use QPainter in QOpenGlWidget's paintGL

Tags:

qt

opengl

I have recently switched from the QGLWidget to the new QOpenGlWidget, because the later one is missing the renderText() function. I am thinking of using QPainter to draw some text over my openGL 3D graphics.

I originally render everything through the paintGL() function, how can I add in a QPainter safely in that function?

My code is like this:

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

    //Where to safely use the QPainter?
}
like image 427
Nyaruko Avatar asked Oct 19 '22 11:10

Nyaruko


1 Answers

Just add QPainter calls right into the paintGL() method.

paintGL()
{
    // OpenGL code...

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

}

The paintGL() function is called by the QOpenGLWidget::paintEvent() so there should not be any problems using the QPainter.

Little 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

like image 158
Tomas Avatar answered Oct 21 '22 06:10

Tomas