PDA

View Full Version : Qt opengl use shader to draw triangle



zhangzhisheng
7th May 2015, 09:31
I just want to draw a triangle with Qt. When I run the program, there is no triangle. What is wrong with my code?


#include "glwidget.h"

GLWidget::GLWidget(QWidget *parent) :QOpenGLWidget(parent)
{
this->setFocusPolicy(Qt::StrongFocus);
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setMajorVersion(4);
format.setMinorVersion(2);
format.setSamples(16);
format.setProfile(QSurfaceFormat::CoreProfile);
setFormat(format);

}

void GLWidget::initializeGL()
{
initializeOpenGLFunctions();
glClearColor(0.13F, 0.13F, 0.14F, 0.0F);
m_shaderProgram.addShaderFromSourceFile(QOpenGLSha der::Vertex,"../PCRP/vertexshadercode.vert");
m_shaderProgram.addShaderFromSourceFile(QOpenGLSha der::Fragment,"../PCRP/fragmentshadercode.frag");
m_shaderProgram.link();
m_MVPMatrixLoc=m_shaderProgram.uniformLocation("u_MVPMatrix");
GLfloat vertex[]={1.0,0.0,0.0,1.0,
0.0,1.0,0.0,1.0,
1.0,1.0,0.0,1.0};
m_Vbo.create();
m_Vbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
m_Vbo.bind();
m_Vbo.allocate(vertex,sizeof(vertex));
m_ViewMatrix.lookAt(QVector3D(0.0f, 0.0f, 1.5f), QVector3D(0.0f, 0.0f, -5.0f), QVector3D(0.0f, 1.0f, 0.0f));

}

void GLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_MULTISAMPLE);
m_shaderProgram.bind();
m_shaderProgram.enableAttributeArray("a_Position");
m_shaderProgram.setAttributeBuffer("a_Position",GL_FLOAT,0,4);

m_ModelMatrix.setToIdentity();
m_MVPMatrix=m_ProjectionMatrix*m_ViewMatrix*m_Mode lMatrix;

m_shaderProgram.setUniformValue(m_MVPMatrixLoc,m_M VPMatrix);
glDrawArrays(GL_TRIANGLES,0,3);

}

void GLWidget::resizeGL(int w, int h)
{
glViewport(0, 0, (GLint)width(), (GLint)height());
m_ProjectionMatrix.setToIdentity();
m_ProjectionMatrix.perspective(45,(float) (width()/height()),0.1f,1000.0f);
}

this is vertexshadercode.vert

attribute vec4 a_Position;

uniform mat4 u_MVPMatrix;

void main()
{

gl_Position = u_MVPMatrix*a_Position;
} ;

this is fragmentshadercode.frag

void main(void)
{
gl_FragColor=vec4(1.0,0.0,0.0,1.0);
}

d_stranz
7th May 2015, 15:57
You don't check the return values from the addShaderFromSource() calls. Do you even know that your shader programs are being loaded?

Try using the addShaderFromSourceCode() version (defining your shader programs as static char * strings - as in the Qt Creator OpenGLWindow example program) and see if you get something different.

At worst, start with the example program and modify it to your needs.