QT5 TUTORIAL OPENGL WITH QGLWIDGET - 2016

本教程介绍如何利用Qt5和OpenGL创建一个可以动态控制XYZ轴旋转的金字塔绘制系统。用户可通过滑块和鼠标操作调整视角。教程涵盖了设置OpenGL环境、添加交互控件及实现旋转逻辑等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 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:

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



PromotedWidgets.png

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:

objectName_myGLWidget.png


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.

SliderRangeSetting.png

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

Sliders_Layout.png


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


PromotedWidgets.png

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:

objectName_myGLWidget.png


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.

SliderRangeSetting.png

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

Sliders_Layout.png


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


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.

Slots_SetXYZRotation.png

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:

AddingSgnals_setXRotation.png


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.

OpenGLQt5Run.png

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_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 &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();
}



Qt 5 Tutorial

  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


from:


http://www.bogotobogo.com/Qt/Qt5_OpenGL_QGLWidget.php
PromotedWidgets.png

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:

objectName_myGLWidget.png


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.

SliderRangeSetting.png

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

Sliders_Layout.png


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值