How to add QOpenGLWidget to QGraphicsScene?

845 views Asked by At

My main.cpp

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QSurfaceFormat format;
    format.setDepthBufferSize(24);
    format.setStencilBufferSize(8);
    format.setVersion(3, 2);
    format.setProfile(QSurfaceFormat::CoreProfile);
    format.setSamples(4);
    QSurfaceFormat::setDefaultFormat(format);

    MyGLWidget w;
    w.setFormat(format);

    QGraphicsScene scene;
    QGraphicsProxyWidget* proxy = scene.addWidget(&w);
    scene.addText("Hello");

    QGraphicsView view(&scene);
    view.show();

    return a.exec();
}

My MyGLWidget.h

class MyGLWidget :
    public QOpenGLWidget
    , protected QOpenGLFunctions
{
public:
    MyGLWidget(QWidget* parent = nullptr);

protected:
    void initializeGL() override;
    void resizeGL(int w, int h) override;
    void paintGL() override;
};

MyGLWidget.cpp

MyGLWidget::MyGLWidget(QWidget* parent) : QOpenGLWidget(parent)
{
}

void MyGLWidget::initializeGL()
{
    initializeOpenGLFunctions();
    glClearColor(1.0f, 0.0f, 1.0f, 1.0f);
}

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

void MyGLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);

    QPainter p(this);
    p.drawText(rect(), Qt::AlignCenter, "Testing");
    p.drawEllipse(100, 100, 100, 100);
}

Output image. enter image description here

It seems that void MyGLWidget::paintGL() wasnt called. How do I call paintGL? Can I set it to auto update rendering?

Also, I get weird exception.

enter image description here

If I made changes like this,

MyGLWidget w;
w.setFormat(format);
w.show();

//QGraphicsScene scene;
//QGraphicsProxyWidget* proxy = scene.addWidget(&w);
//scene.addText("Hello");

//QGraphicsView view(&scene);
//view.show();

I get this. Which means that OpenGL rendering works fine. enter image description here

0

There are 0 answers