initializeGL()函数:
initializeOpenGLFunctions();
//创建VBO和VAO对象,并赋予ID
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
//绑定VBO和VAO对象
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
//为当前绑定到target的缓冲区对象创建一个新的数据存储。
//如果data不是NULL,则使用来自此指针的数据初始化数据存储
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//告知显卡如何解析缓冲里的属性值
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
//开启VAO管理的第一个属性值
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, 0);
bool success;
shaderProgram.addShaderFromSourceFile(QOpenGLShader::Vertex, "shaders/shapes.vert");
shaderProgram.addShaderFromSourceFile(QOpenGLShader::Fragment, "shaders/shapes.frag");
success = shaderProgram.link();
if (!success)
qDebug() << "ERR:" << shaderProgram.log();
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_DYNAMIC_DRAW);
textureWall = new QOpenGLTexture(QOpenGLTexture::Target2D);
textureWall->create();
textureWall->setFormat(QOpenGLTexture::DepthFormat);//设置纹理像素格式
textureWall->setSize(1404, 1092);//设置纹理宽、高
textureWall->allocateStorage();
shaderProgram.bind();
shaderProgram.setUniformValue("textureWall", 0);
glBindVertexArray(0);
paintGL()函数:
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
shaderProgram.bind();
glBindVertexArray(VAO);
textureWall->bind();
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, NULL);
textureWall->release();
textureWall->destroy();
textureWall->create();
on_timeout槽函数:
int data = qrand() % 4 + 1;
QString basePath = "images/";
QString path = basePath + QString::number(data).append(".tiff");
QByteArray cdata = path.toLocal8Bit();
cv::Mat imgm = imread(std::string(cdata), cv::IMREAD_UNCHANGED);
for (int i = 0; i < imgm.rows; i++) {
for (int j = 0; j < imgm.cols; j++) {
m_img8bit[i * imgm.cols + j] = imgm.at<uchar>(i, j);
}
}
QImage images(m_img8bit, 1404, 1092, QImage::Format_Grayscale8);
//QImage resimg = images.convertToFormat(QImage::Format_RGB888);
textureWall->setData(images);
update();
顶点坐标:
float vertices[] = {
// positions // colors // texture coords
1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
unsigned int indices[] = { // note that we start from 0!
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};