class MyGLWidget : public QOpenGLWidget, protected QOpenGLFunctions { Q_OBJECT public: MyGLWidget(QWidget *parent = nullptr) : QOpenGLWidget(parent) {} void setImage(cv::Mat image) { m_image = image; update(); } void stopImage(bool) {} protected: protected: void initializeGL() override { initializeOpenGLFunctions(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // 创建并绑定纹理 glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } void resizeGL(int w, int h) override { glViewport(0, 0, w, h); } void paintGL() override { // 从VideoCapture对象中读取图像数据 makeCurrent(); // 设置当前OpenGL上下文 // 从VideoCapture对象中读取图像数据 // 将图像数据上传到纹理中 if (!m_image.empty()) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_image.cols, m_image.rows, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, m_image.data); } // 清除帧缓冲区 glClear(GL_COLOR_BUFFER_BIT); // 渲染纹理 if (!m_image.empty()) { glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, -1.0f, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, -1.0f, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 0.0f); glEnd(); glDisable(GL_TEXTURE_2D); } } private: cv::Mat m_image; GLuint m_texture{}; }; glClear(GL_COLOR_BUFFER_BIT);此处崩溃,分析原因并修改
时间: 2024-03-27 22:40:33 浏览: 98
根据代码分析,glClear(GL_COLOR_BUFFER_BIT)在paintGL()函数中被调用,可能是因为OpenGL上下文没有被正确地设置导致程序崩溃。为了避免程序崩溃,可以在调用glClear(GL_COLOR_BUFFER_BIT)之前添加makeCurrent()函数来确保OpenGL上下文被正确地设置。修改后的代码如下:
```
void paintGL() override {
makeCurrent(); // 设置当前OpenGL上下文
// 从VideoCapture对象中读取图像数据
// 将图像数据上传到纹理中
if (!m_image.empty()) {
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_image.cols, m_image.rows, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, m_image.data);
}
// 清除帧缓冲区
makeCurrent(); // 再次设置当前OpenGL上下文
glClear(GL_COLOR_BUFFER_BIT);
// 渲染纹理
if (!m_image.empty()) {
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, -1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, -1.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 0.0f);
glEnd();
glDisable(GL_TEXTURE_2D);
}
}
```
阅读全文