实现第一个Qt的opengl窗口
效果图:
源码实现:
在工程文件中添加QT += opengl
**
- mainwindow.h
**
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QOpenGLWindow>
#include <QOpenGLFunctions>
//继承QOpenGLWindow或QOpenGLWidget and //QOpenGLFunctions
class MainWindow : public QOpenGLWindow,protected QOpenGLFunctions
{
Q_OBJECT
public:
~MainWindow();
//重写QOpenGLWindow的下面三个函数
void initializeGL(); //初始化
void resizeGL(int width, int height);//绘制窗口大小
void paintGL();//重新绘制窗口图像
private:
void printContextInformation();//获取调试信息
};
#endif // MAINWINDOW_H
**
2.mainwindow.cpp
**
#include "mainwindow.h"
#include <QDebug>
MainWindow::~MainWindow()
{
}
void MainWindow::initializeGL(){
initializeOpenGLFunctions();
printContextInformation();
glClearColor(0.0f,0.0f,1.0f,1.0f);//设置颜色
}
void MainWindow::resizeGL(int width, int height)
{
//未作处理
}
void MainWindow::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT);
}
// 打印相关信息,调试用
void MainWindow::printContextInformation()\
{
QString glType;
QString glVersion;
QString glProfile;
glType = (context()->isOpenGLES())?"OpenGL ES":"OpenGL";
glVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));
#define CASE(c) case QSurfaceFormat::c: glProfile = #c; break
switch (format().profile()) {
CASE(NoProfile);
CASE(CoreProfile);
CASE(CompatibilityProfile); //??
}
#undef CASE
qDebug() << qPrintable(glType) << qPrintable(glVersion)<< "(" << qPrintable(glProfile) << ")";
}
**
- main.cpp
**
#include "mainwindow.h"
#include <QApplication>
#include <QGLFormat>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 设置 OpenGL 信息
// 注意:必须在show()之前设置信息
// QSurfaceFormat format;
// format.setRenderableType(QSurfaceFormat::OpenGL);
// format.setProfile(QSurfaceFormat::CoreProfile);
// format.setVersion(3,3);
MainWindow w;
// w.setFormat(format);
w.resize(QSize(800, 600));
w.show();
return a.exec();
}