Qt5 Tutorial OpenGL with QGLWidget - 2020
In this tutorial, we will learn how to use OpenGL with QT5.
We will be building a pyramid drawing system that will allow the user to dynamically control the xyz rotation with QSlider and with mouse.
After this tutorial, we will understand the basics of creating, moving, and coloring objects using OpenGL. But this tutorial is more focused on Qt and Creator IDE rather than the details of OpenGL implementation.
If we know both Qt and OpenGL, the essence of Qt OpenGL is two step learning process:
- Getting OpenGL module from Qt.
- Putting OpenGL aware canvas into QT UI
Note that the header file is automatically filled in for us, and click Add.
With the MyGLWidget class selected, click Promote.
Let's rename this object to myGLWidget:
We want to control rotation with QSliders. Let's add them:
Name them: xRotSlider, yRotSlider, zRotSlider.
Set the range: minimum = 0 and maximum = 360, singleStep = 16, page step = 15, tickPosition = TickAbove, and tickinterval = 15.
Then, put all of the UI components into appropriate layouts as shown in the picture below.
The three methods we will need to include are:
- initializeGL() which will be called to initialize the GL Context.
- resizeGL() which will be called when the widget is resized.
- paintGL() which will be called when the OpenGL widget needs to be redrawn.
Declare all three as protected methods in the myglwidget.h header file:
protected: void initializeGL(); void paintGL(); void resizeGL(int width, int height);
We'll also need to declare the private variables:
private: int xRot; int yRot; int zRot;
Here are slots for myglwidget.h:
public slots: // slots for xyz-rotation slider void setXRotation(int angle); void setYRotation(int angle); void setZRotation(int angle);
Our pyramid will rotate in two ways: (1)by the slider ui (2)by mouse.
Now, let's make some connections between signals and slots.
As shown in the picture above, we setup the slots for the sliders. Note that the slots such as setXRotation(int) is not in the slot list, and we need to add it to the list as shown in the following picture:
Here are signals to emit when there is a rotation from mouse movement and should be placed for myglwidget.h:
signals: // signaling rotation from mouse movement void xRotationChanged(int angle); void yRotationChanged(int angle); void zRotationChanged(int angle);
Here is the screen shot of a run.
Here is the video shot of a run.
Source file: MyOpenGL.zip
main.cpp:
// main.cpp #include <QApplication> #include <QDesktopWidget> #include "window.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); Window window; window.resize(window.sizeHint()); int desktopArea = QApplication::desktop()->width() * QApplication::desktop()->height(); int widgetArea = window.width() * window.height(); window.setWindowTitle("OpenGL with Qt"); if (((float)widgetArea / (float)desktopArea) < 0.75f) window.show(); else window.showMaximized(); return app.exec(); }
window.h:
// window.h #ifndef WINDOW_H #define WINDOW_H #include <QWidget> #include <QSlider> namespace Ui { class Window; } class Window : public QWidget { Q_OBJECT public: explicit Window(QWidget *parent = 0); ~Window(); protected: void keyPressEvent(QKeyEvent *event); private: Ui::Window *ui; }; #endif // WINDOW_H
window.cpp:
// window.cpp #include <QtWidgets> #include "window.h" #include "ui_window.h" #include "myglwidget.h" Window::Window(QWidget *parent) : QWidget(parent), ui(new Ui::Window) { ui->setupUi(this); connect(ui->myGLWidget, SIGNAL(xRotationChanged(int)), ui->rotXSlider, SLOT(setValue(int))); connect(ui->myGLWidget, SIGNAL(yRotationChanged(int)), ui->rotYSlider, SLOT(setValue(int))); connect(ui->myGLWidget, SIGNAL(zRotationChanged(int)), ui->rotZSlider, SLOT(setValue(int))); } Window::~Window() { delete ui; } void Window::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) close(); else QWidget::keyPressEvent(e); }
myglwidget.h:
// myglwidget.h #ifndef MYGLWIDGET_H #define MYGLWIDGET_H #include <QGLWidget> class MyGLWidget : public QGLWidget { Q_OBJECT public: explicit MyGLWidget(QWidget *parent = 0); ~MyGLWidget(); signals: public slots: protected: void initializeGL(); void paintGL(); void resizeGL(int width, int height); QSize minimumSizeHint() const; QSize sizeHint() const; void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); public slots: // slots for xyz-rotation slider void setXRotation(int angle); void setYRotation(int angle); void setZRotation(int angle); signals: // signaling rotation from mouse movement void xRotationChanged(int angle); void yRotationChanged(int angle); void zRotationChanged(int angle); private: void draw(); int xRot; int yRot; int zRot; QPoint lastPos; }; #endif // MYGLWIDGET_H
myglwidget.cpp:
// myglwidget.cpp #include <QtWidgets> #include <QtOpenGL> #include "myglwidget.h" MyGLWidget::MyGLWidget(QWidget *parent) : QGLWidget(QGLFormat(QGL::SampleBuffers), parent) { xRot = 0; yRot = 0; zRot = 0; } MyGLWidget::~MyGLWidget() { } QSize MyGLWidget::minimumSizeHint() const { return QSize(50, 50); } QSize MyGLWidget::sizeHint() const { return QSize(400, 400); } static void qNormalizeAngle(int ∠) { while (angle < 0) angle += 360 * 16; while (angle > 360) angle -= 360 * 16; } void MyGLWidget::setXRotation(int angle) { qNormalizeAngle(angle); if (angle != xRot) { xRot = angle; emit xRotationChanged(angle); updateGL(); } } void MyGLWidget::setYRotation(int angle) { qNormalizeAngle(angle); if (angle != yRot) { yRot = angle; emit yRotationChanged(angle); updateGL(); } } void MyGLWidget::setZRotation(int angle) { qNormalizeAngle(angle); if (angle != zRot) { zRot = angle; emit zRotationChanged(angle); updateGL(); } } void MyGLWidget::initializeGL() { qglClearColor(Qt::black); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glShadeModel(GL_SMOOTH); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); static GLfloat lightPosition[4] = { 0, 0, 10, 1.0 }; glLightfv(GL_LIGHT0, GL_POSITION, lightPosition); } void MyGLWidget::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(0.0, 0.0, -10.0); glRotatef(xRot / 16.0, 1.0, 0.0, 0.0); glRotatef(yRot / 16.0, 0.0, 1.0, 0.0); glRotatef(zRot / 16.0, 0.0, 0.0, 1.0); draw(); } void MyGLWidget::resizeGL(int width, int height) { int side = qMin(width, height); glViewport((width - side) / 2, (height - side) / 2, side, side); glMatrixMode(GL_PROJECTION); glLoadIdentity(); #ifdef QT_OPENGL_ES_1 glOrthof(-2, +2, -2, +2, 1.0, 15.0); #else glOrtho(-2, +2, -2, +2, 1.0, 15.0); #endif glMatrixMode(GL_MODELVIEW); } void MyGLWidget::mousePressEvent(QMouseEvent *event) { lastPos = event->pos(); } void MyGLWidget::mouseMoveEvent(QMouseEvent *event) { int dx = event->x() - lastPos.x(); int dy = event->y() - lastPos.y(); if (event->buttons() & Qt::LeftButton) { setXRotation(xRot + 8 * dy); setYRotation(yRot + 8 * dx); } else if (event->buttons() & Qt::RightButton) { setXRotation(xRot + 8 * dy); setZRotation(zRot + 8 * dx); } lastPos = event->pos(); } void MyGLWidget::draw() { qglColor(Qt::red); glBegin(GL_QUADS); glNormal3f(0,0,-1); glVertex3f(-1,-1,0); glVertex3f(-1,1,0); glVertex3f(1,1,0); glVertex3f(1,-1,0); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(0,-1,0.707); glVertex3f(-1,-1,0); glVertex3f(1,-1,0); glVertex3f(0,0,1.2); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(1,0, 0.707); glVertex3f(1,-1,0); glVertex3f(1,1,0); glVertex3f(0,0,1.2); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(0,1,0.707); glVertex3f(1,1,0); glVertex3f(-1,1,0); glVertex3f(0,0,1.2); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(-1,0,0.707); glVertex3f(-1,1,0); glVertex3f(-1,-1,0); glVertex3f(0,0,1.2); glEnd(); }
Qt 5 Tutorial
- Hello World
- Signals and Slots
- Q_OBJECT Macro
- MainWindow and Action
- MainWindow and ImageViewer using Designer A
- MainWindow and ImageViewer using Designer B
- Layouts
- Layouts without Designer
- Grid Layouts
- Splitter
- QDir
- QFile (Basic)
- Resource Files (.qrc)
- QComboBox
- QListWidget
- QTreeWidget
- QAction and Icon Resources
- QStatusBar
- QMessageBox
- QTimer
- QList
- QListIterator
- QMutableListIterator
- QLinkedList
- QMap
- QHash
- QStringList
- QTextStream
- QMimeType and QMimeDatabase
- QFile (Serialization I)
- QFile (Serialization II - Class)
- Tool Tips in HTML Style and with Resource Images
- QPainter
- QBrush and QRect
- QPainterPath and QPolygon
- QPen and Cap Style
- QBrush and QGradient
- QPainter and Transformations
- QGraphicsView and QGraphicsScene
- Customizing Items by inheriting QGraphicsItem
- QGraphicsView Animation
- FFmpeg Converter using QProcess
- QProgress Dialog - Modal and Modeless
- QVariant and QMetaType
- QtXML - Writing to a file
- QtXML - QtXML DOM Reading
- QThreads - Introduction
- QThreads - Creating Threads
- Creating QThreads using QtConcurrent
- QThreads - Priority
- QThreads - QMutex
- QThreads - GuiThread
- QtConcurrent QProgressDialog with QFutureWatcher
- QSemaphores - Producer and Consumer
- QThreads - wait()
- MVC - ModelView with QListView and QStringListModel
- MVC - ModelView with QTreeView and QDirModel
- MVC - ModelView with QTreeView and QFileSystemModel
- MVC - ModelView with QTableView and QItemDelegate
- QHttp - Downloading Files
- QNetworkAccessManager and QNetworkRequest - Downloading Files
- Qt's Network Download Example - Reconstructed
- QNetworkAccessManager - Downloading Files with UI and QProgressDialog
- QUdpSocket
- QTcpSocket
- QTcpSocket with Signals and Slots
- QTcpServer - Client and Server
- QTcpServer - Loopback Dialog
- QTcpServer - Client and Server using MultiThreading
- QTcpServer - Client and Server using QThreadPool
- Asynchronous QTcpServer - Client and Server using QThreadPool
- Qt Quick2 QML Animation - A
- Qt Quick2 QML Animation - B
- Short note on Ubuntu Install
- OpenGL with QT5
- Qt5 Webkit : Web Browser with QtCreator using QWebView Part A
- Qt5 Webkit : Web Browser with QtCreator using QWebView Part B
- Video Player with HTML5 QWebView and FFmpeg Converter
- Qt5 Add-in and Visual Studio 2012
- Qt5.3 Installation on Ubuntu 14.04
- Qt5.5 Installation on Ubuntu 14.04
- Short note on deploying to Windows
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization