Skip to content

Instantly share code, notes, and snippets.

Created March 2, 2017 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/625e69dd61f0685c1cae625bdefbac74 to your computer and use it in GitHub Desktop.
Save anonymous/625e69dd61f0685c1cae625bdefbac74 to your computer and use it in GitHub Desktop.
Mixing OpenGL and QPainter in QOpenGLWidget
#include <QApplication>
#include <QMainWindow>
#include <QHBoxLayout>
#include <QGLWidget>
#include <QOpenGLContext>
#include <QDebug>
#include <QPainter>
#include <QOpenGLWidget>
class Widget : public QOpenGLWidget
{
Q_OBJECT
public:
Widget(QWidget *parent=nullptr)
: QOpenGLWidget(parent)
{ }
public:
void initializeGL() {
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 resizeGL(int width, int height) {
glViewport(0, 0, width, height);
}
void paintGL() {
qDebug() << "Error 1: " << glGetError();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0, 0.0);
glVertex3f(-0.5f, -0.5f, 0);
glColor3f(0.0, 1.0f, 0.0);
glVertex3f(0.5f, -0.5f, 0.0);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 0.5f, 0);
glEnd();
QPainter p(this);
p.setPen(Qt::red);
p.drawLine(rect().topLeft(), rect().bottomRight());
qDebug() << "Error 2: " << glGetError();
}
};
int main(int argc, char *argv[])
{
/* Note: Calling QSurfaceFormat::setDefaultFormat() before
constructing the QApplication instance is mandatory on some
platforms (for example, OS X) when an OpenGL core profile context
is requested. This is to ensure that resource sharing between
contexts stays functional as all internal contexts are created
using the correct version and profile. */
QSurfaceFormat fmt;
if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL) {
fmt.setVersion(2,1);
fmt.setProfile(QSurfaceFormat::CoreProfile);
fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
fmt.setOption(QSurfaceFormat::DebugContext);
} else {
fmt.setVersion(3, 0);
}
QSurfaceFormat::setDefaultFormat(fmt);
QApplication::setDesktopSettingsAware(false);
QApplication app(argc, argv);
Widget win;
win.show();
return app.exec();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment