C++ QGLWidget:使用setFormat()启用多重采样=窗口不';关不上

C++ QGLWidget:使用setFormat()启用多重采样=窗口不';关不上,c++,qt,events,opengl,C++,Qt,Events,Opengl,我正在用Qt4在OpenGL中制作一个简单的三角形,它工作得很好,直到我使用set格式启用多重采样。这是我的密码: #include <QApplication> #include <QtOpenGL> // gl window class class GLWindow : public QGLWidget { public: GLWindow(QWidget *parent = nullptr) : QGLWidget(parent){} pro

我正在用Qt4在OpenGL中制作一个简单的三角形,它工作得很好,直到我使用set格式启用多重采样。这是我的密码:

#include <QApplication>
#include <QtOpenGL>
// gl window class
class GLWindow : public QGLWidget
{
public:
    GLWindow(QWidget *parent = nullptr)
        : QGLWidget(parent){}
protected:
    // ALL THE FOLLOWING FUNCTIONS ARE OVERRIDDEN FROM QGLWIDGET 
    void initializeGL()
    {
        QGLFormat newFormat = this->format();
        newFormat.setSampleBuffers(true);
        newFormat.setSamples(16);
        this->setFormat(newFormat);
    }
    void resizeGL(int w, int h)
    {
        glViewport(0, 0, w, h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-1, 1, -1, 1, -1, 1);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
    }
    void paintGL()
    {
        glClear(GL_COLOR_BUFFER_BIT);
        glBegin(GL_TRIANGLES);
            glColor3f(1, 0, 0);
            glVertex2f(0, 1);
            glColor3f(0, 1, 0);
            glVertex2f(1, -1);
            glColor3f(0, 0, 1);
            glVertex2f(-1, -1);
        glEnd();
    }
};
// main function
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    GLWindow window;
    window.resize(640, 480);
    window.show();
    return app.exec();
}

您不应该从
initializeGL
调用
setFormat
,因为它会触发对
initializeGL
本身的调用。由于qt4.8中有
QGLWidget::setFormat
,所以根本不应该使用它


因此,首先尝试从构造函数调用
setFormat
,然后,如果它不起作用(或者即使它起作用),尝试从
main()

将格式传递给
QGLWidget
的构造函数。太棒了,我将格式传递给了QGLWidget的构造函数,现在就可以了!非常感谢你:D
QT += core
QT += gui
QT += opengl

SOURCES += \
    main.cpp