qt opengl显示qimage 头文件源文件以及pro文件 简单程序
时间: 2024-02-20 20:58:31 浏览: 166
opengl头文件和源文件库文件
以下是一个简单的Qt OpenGL显示QImage的示例程序,包括头文件、源文件和.pro文件:
**main.cpp:**
```cpp
#include <QApplication>
#include "glwidget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GLWidget w;
w.show();
return a.exec();
}
```
**glwidget.h:**
```cpp
#ifndef GLWIDGET_H
#define GLWIDGET_H
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QImage>
class GLWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
Q_OBJECT
public:
GLWidget(QWidget *parent = nullptr);
~GLWidget();
protected:
void initializeGL() override;
void resizeGL(int width, int height) override;
void paintGL() override;
private:
QImage m_image;
GLuint m_texture;
};
#endif // GLWIDGET_H
```
**glwidget.cpp:**
```cpp
#include "glwidget.h"
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QDebug>
GLWidget::GLWidget(QWidget *parent)
: QOpenGLWidget(parent)
{
m_image.load(":/image.png");
}
GLWidget::~GLWidget()
{
makeCurrent();
glDeleteTextures(1, &m_texture);
doneCurrent();
}
void GLWidget::initializeGL()
{
initializeOpenGLFunctions();
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
// Load image into texture
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_image.width(), m_image.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, m_image.bits());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
void GLWidget::resizeGL(int width, int height)
{
glViewport(0, 0, width, height);
}
void GLWidget::paintGL()
{
// Clear background
glClear(GL_COLOR_BUFFER_BIT);
// Draw texture
QOpenGLShaderProgram program;
program.addShaderFromSourceCode(QOpenGLShader::Vertex, "attribute vec2 position; varying vec2 texCoord; void main() { gl_Position = vec4(position, 0.0, 1.0); texCoord = position * 0.5 + 0.5; }");
program.addShaderFromSourceCode(QOpenGLShader::Fragment, "uniform sampler2D texture; varying vec2 texCoord; void main() { gl_FragColor = texture2D(texture, texCoord); }");
program.link();
program.bind();
program.setUniformValue("texture", 0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(0);
}
```
**glwidget.pro:**
```
QT += opengl
CONFIG += c++11
SOURCES += \
main.cpp \
glwidget.cpp
HEADERS += \
glwidget.h
```
注意,这个示例程序中使用了一个image.png的图片文件。在项目文件中必须将其添加到资源中,否则会报文件找不到的错误。
阅读全文