背景颜色在Qt和opengl

background color in Qt and opengl

本文关键字:opengl Qt 颜色 背景      更新时间:2023-10-16

我在QtCreator中实现了一个简单的2D opengl类。没什么特别的,但是当我用glOrtho设置场景时,我无法将背景色设置为唯一。

下面是带有注释的试验代码:

#include "glwidget.h"
#include <iostream>
GLWidget::GLWidget(QWidget *parent) :
    QGLWidget(parent) {}

void GLWidget::initializeGL() {
    std::cout << "GLWidget::initializeGL" << std::endl;
    glShadeModel(GL_SMOOTH);
    glClearDepth(1.0f);
    glDepthFunc(GL_LEQUAL);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}
void GLWidget::resizeGL(int width, int height) {    
    std::cout << "GLWidget::resizeGL" << std::endl;
    makeCurrent();
    glViewport(0,0,(GLint)width, (GLint)height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, width, 0, height);
    glScalef(1, -1, 1);                 // invert Y axis so increasing Y goes down.
    glTranslatef(0, -height, 0);       // shift origin up to upper-left corner.
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    frameCount = 0;
    glClearColor(0.0f, 255.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    //updateGL();   // this doesn't produce any changes
}
void GLWidget::paintGL() {
    std::cout << "GLWidget::paintGL" << std::endl;
    makeCurrent();
//    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // this works but it is in paintGL
//    glLoadIdentity();
}

的事实是,我想设置背景颜色只有一次,所有的paintGL通过updateGL每次鼠标移动不清理背景。因此,paintGL中的注释行(有效地使背景变为绿色)必须保持注释。

肯定有一些更新的东西调用,但我不明白在哪里…

如果你想只上色一次,使用initializeGL();

void GLWidget::initializeGL()
{
    glEnable(GL_LIGHTING);glEnable(GL_LIGHT0);
    glClearColor(1, 0, 0, 1); //sets a red background
    glEnable(GL_DEPTH_TEST);
}
void GLWidget::paintGL() //countinous loop call
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //your code, paintGL() is looped continously to draw output.
    //hence setting background here is never good, may cause flickering.
}
void GLWidget::resizeGL(int w, int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0, (GLdouble)w/h, 0.01, 100.0);
}