Nyaruko
Nyaruko

Reputation: 4459

How to use QPainter in QOpenGlWidget's paintGL

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?
}

Upvotes: 6

Views: 7135

Answers (2)

Chris
Chris

Reputation: 253

you should use QPainter in paintGL() like this:

paintGL()
{
    QPainter painter(this);
    //painter.draw();
    painter.beginNativePainting();
    //Opengl api
    painter.endNativePainting();
    painter.end();
}

But I find that texture can't be painted in this way.

Upvotes: 1

Tomas
Tomas

Reputation: 2210

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

Upvotes: 5

Related Questions