简体   繁体   中英

background color in Qt and opengl

I'm implementing a simple 2D opengl class in qt 4.8 with QtCreator. Nothing special, but I'm not able to set the background color oly one when I'm setting up the scene with glOrtho.

here is the code with some commented trials:

#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();
}

the fact is that i want to set the background color only once and all paintGL via updateGL each mouse movement WITHOUT cleaning the background. So the commented lines in the paintGL (that effectivly make the background green) has to keep commented.

For sure there is some update-something to call but I don't understan where..

If you want to color only once, use 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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM