I’m making a simple triangle in OpenGL with Qt4, and it works fine, until I use set format to enable multisampling. Here is my code:
#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();
}
Before I added the format stuff in “initlializeGL”, it worked fine (obviously except no multisampling).
Then, I add the format stuff and the window does not close. And when I say this I mean that it will not close when I press the “X” button on the top right corner, or it will not even close when I make a call to the window’s “close()” function.
Furthermore, It makes a call to “closeEvent()” when you press the “X” button (I checked), but nothing actually closes. I tried making a call to “close()” inside my overridden “closeEvent()” function, but it did nothing.
Once again, I remove the code in “initializeGL()”, and then it closes fine. So, I try to move the code I have in “initializeGL()” into the constructor. The multisampling works, and it closes when I press “X”. Great! Except I get this after the window closes:

So that is that. In a nutshell:
- Everything works fine when there is no “setFormat()” related code in “initializeGL()”.
- When I do put my “setFormat()” related code in “initializeGL()”, the window doesn’t close.
- When I put my “setFormat()” related code in the constructor, I get the weird error shown in the above image when the window is closed;
So how to I get the window to close, while keeping multisampling enabled and without getting some dumb error after the window is closed?
EDIT: Here is the text in my .pro file
QT += core
QT += gui
QT += opengl
SOURCES += \
main.cpp
You shouldn’t call
setFormatfrominitializeGL, as it triggers a call toinitializeGLitself. And sinceQGLWidget::setFormatis obsolete in Qt 4.8, you shouldn’t use it at all.So, first try calling
setFormatfrom the constructor, then, if it doesn’t work (or even if it works), try passing the format to the constructor ofQGLWidgetfrommain().