How to add QOpenGLWidget to QGraphicsScene?

浪尽此生 提交于 2020-01-15 10:57:07

问题


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.

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.

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.

来源:https://stackoverflow.com/questions/57553945/how-to-add-qopenglwidget-to-qgraphicsscene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!