程序运行截图如下:
代码如下:
MyFrisstMSVCQt.h
#pragma once
#include <QtWidgets/QWidget>
#include "ui_MyFristMSVCQt.h"
class MyFristMSVCQt : public QWidget
{
Q_OBJECT
public:
MyFristMSVCQt(QWidget *parent = Q_NULLPTR);
void timerEvent(QTimerEvent *event);
private:
Ui::MyFristMSVCQtClass ui;
};
MyGLWidget.h
#pragma once
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
class MyGLWidget:public QOpenGLWidget,protected QOpenGLFunctions
{
Q_OBJECT
public:
MyGLWidget(QWidget *parent = 0);
~MyGLWidget();
void setRGB_red(const int value);
void setRGB_blue(const int value);
void setRGB_green(const int value);
protected:
void initializeGL();
void paintGL();
void resizeGL(int w, int h);
protected:
int m_redValue;
int m_blueValue;
int m_greenValue;
};
main.cpp
#include "MyFristMSVCQt.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyFristMSVCQt w;
w.show();
return a.exec();
}
MyFristMSVCQt.cpp
#include "MyFristMSVCQt.h"
#include "ui_MyFristMSVCQt.h"
#include <QTimer>
#include <QDebug>
#include <QTime>
MyFristMSVCQt::MyFristMSVCQt(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
this->setWindowTitle("MyFirstOPenGL");
qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
startTimer(200);
}
void MyFristMSVCQt::timerEvent(QTimerEvent *event)
{
Q_UNUSED(event)
int numRed = qrand() % 256;
int numGreen = qrand() % 256;
int numBlue = qrand() % 256;
ui.openGLWidget->setRGB_blue(numBlue);
ui.openGLWidget->setRGB_green(numGreen);
ui.openGLWidget->setRGB_red(numRed);
ui.openGLWidget->update();
}
MyFLWidget.cpp
#include "MyGLWidget.h"
#include <gl/GLU.h>
#include <QDebug>
MyGLWidget::MyGLWidget(QWidget *parent)
: QOpenGLWidget(parent)
{
}
MyGLWidget::~MyGLWidget()
{
}
void MyGLWidget::setRGB_blue(const int value)
{
m_blueValue = value;
}
void MyGLWidget::setRGB_green(const int value)
{
m_greenValue = value;
}
void MyGLWidget::setRGB_red(const int value)
{
m_redValue = value;
}
void MyGLWidget::initializeGL()
{
initializeOpenGLFunctions();
glMatrixMode(GL_PROJECTION);
gluPerspective(50.0f, 800.0f / 600.0f, 0.1f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void MyGLWidget::paintGL()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glColor4ub(m_blueValue, m_greenValue, m_redValue, 255);
glVertex3f(-0.2f, -0.2f, -0.5f);
glColor4ub(m_redValue, m_greenValue, m_blueValue, 255);
glVertex3f(0.2f, -0.2f, -0.5f);
glColor4ub(m_greenValue, m_redValue, m_blueValue, 255);
glVertex3f(0.0f, 0.2f, -0.5f);
glEnd();
}
void MyGLWidget::resizeGL(int w, int h)
{
Q_UNUSED(w)
Q_UNUSED(h)
}