Qt5 Tutorial OpenGL with QGLWidget (2024)

Qt5 Tutorial OpenGL with QGLWidget (1)



bogotobogo.com site search:

1. Introduction

In this tutorial, we will learn how to use OpenGL with QT5.

We will be building a pyramid drawing system that will allow the userto 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:

  1. Getting OpenGL module from Qt.
  2. Putting OpenGL aware canvas into QT UI

Qt5 Tutorial OpenGL with QGLWidget (2)

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:

Qt5 Tutorial OpenGL with QGLWidget (3)

6. Adding Sliders and set the Layout

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.

Qt5 Tutorial OpenGL with QGLWidget (4)

Then, put all of the UI components into appropriate layouts as shown in the picture below.

Qt5 Tutorial OpenGL with QGLWidget (5)

7. Coding OpenGL Canvas, MyGLWidet

The three methods we will need to include are:

  1. initializeGL() which will be called to initialize the GL Context.
  2. resizeGL() which will be called when the widget is resized.
  3. paintGL() which will be called when the OpenGL widget needs to be redrawn.

Declare all three as protected methods in themyglwidget.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;

8. Connecting Sliders to OpenGL Canvas


8.1 Rotation Slider

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.

Qt5 Tutorial OpenGL with QGLWidget (6)

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:

Qt5 Tutorial OpenGL with QGLWidget (7)

8.2 Rotation by Mouse Movements

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);

9. Run Time


9.1 Screen Shot

Here is the screen shot of a run.

Qt5 Tutorial OpenGL with QGLWidget (8)

9.2 Video

Here is the video shot of a run.

10. Source Code

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_OBJECTpublic: 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_OBJECTpublic: 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 &angle;){ 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();}

  1. Hello World
  2. Signals and Slots
  3. Q_OBJECT Macro
  4. MainWindow and Action
  5. MainWindow and ImageViewer using Designer A
  6. MainWindow and ImageViewer using Designer B
  7. Layouts
  8. Layouts without Designer
  9. Grid Layouts
  10. Splitter
  11. QDir
  12. QFile (Basic)
  13. Resource Files (.qrc)
  14. QComboBox
  15. QListWidget
  16. QTreeWidget
  17. QAction and Icon Resources
  18. QStatusBar
  19. QMessageBox
  20. QTimer
  21. QList
  22. QListIterator
  23. QMutableListIterator
  24. QLinkedList
  25. QMap
  26. QHash
  27. QStringList
  28. QTextStream
  29. QMimeType and QMimeDatabase
  30. QFile (Serialization I)
  31. QFile (Serialization II - Class)
  32. Tool Tips in HTML Style and with Resource Images
  33. QPainter
  34. QBrush and QRect
  35. QPainterPath and QPolygon
  36. QPen and Cap Style
  37. QBrush and QGradient
  38. QPainter and Transformations
  39. QGraphicsView and QGraphicsScene
  40. Customizing Items by inheriting QGraphicsItem
  41. QGraphicsView Animation
  42. FFmpeg Converter using QProcess
  43. QProgress Dialog - Modal and Modeless
  44. QVariant and QMetaType
  45. QtXML - Writing to a file
  46. QtXML - QtXML DOM Reading
  47. QThreads - Introduction
  48. QThreads - Creating Threads
  49. Creating QThreads using QtConcurrent
  50. QThreads - Priority
  51. QThreads - QMutex
  52. QThreads - GuiThread
  53. QtConcurrent QProgressDialog with QFutureWatcher
  54. QSemaphores - Producer and Consumer
  55. QThreads - wait()
  56. MVC - ModelView with QListView and QStringListModel
  57. MVC - ModelView with QTreeView and QDirModel
  58. MVC - ModelView with QTreeView and QFileSystemModel
  59. MVC - ModelView with QTableView and QItemDelegate
  60. QHttp - Downloading Files
  61. QNetworkAccessManager and QNetworkRequest - Downloading Files
  62. Qt's Network Download Example - Reconstructed
  63. QNetworkAccessManager - Downloading Files with UI and QProgressDialog
  64. QUdpSocket
  65. QTcpSocket
  66. QTcpSocket with Signals and Slots
  67. QTcpServer - Client and Server
  68. QTcpServer - Loopback Dialog
  69. QTcpServer - Client and Server using MultiThreading
  70. QTcpServer - Client and Server using QThreadPool
  71. Asynchronous QTcpServer - Client and Server using QThreadPool
  72. Qt Quick2 QML Animation - A
  73. Qt Quick2 QML Animation - B
  74. Short note on Ubuntu Install
  75. OpenGL with QT5
  76. Qt5 Webkit : Web Browser with QtCreator using QWebView Part A
  77. Qt5 Webkit : Web Browser with QtCreator using QWebView Part B
  78. Video Player with HTML5 QWebView and FFmpeg Converter
  79. Qt5 Add-in and Visual Studio 2012
  80. Qt5.3 Installation on Ubuntu 14.04
  81. Qt5.5 Installation on Ubuntu 14.04
  82. Short note on deploying to Windows

Qt5 Tutorial OpenGL with QGLWidget (2024)
Top Articles
Latest Posts
Article information

Author: Otha Schamberger

Last Updated:

Views: 5924

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.