简体   繁体   中英

Qt QOpenGLWidget glClearColor not functioning correctly

I have a slight problem when calling glClearColor from various places outside of paintGL(). The aim is to enable the user to set the clear colour on the fly but this is not working as planned unless glClearColor is called each frame in paintGL.

Aim:

void GLWidget::mousePressEvent(QMouseEvent *event)
{
    m_lastPos = event->pos();
    glClearColor(1.0f, 0.0f, 0.0f, 1.0f); //<-- Doesn't change clear colour
}

Non-optimal workaround:

void GLWidget::mousePressEvent(QMouseEvent *event)
{
    m_lastPos = event->pos();
    r = 1.0f;
    g = 0.0f;
    b = 0.0f;
    a = 1.0f;
}

void GLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glClearColor(r, g, b, a);
...

I assume this has something to do with how Qt swaps buffers and updates the screen but it's not clear what exactly is causing it. Any ideas would be great, thanks.

I assume this has something to do with how Qt swaps buffers and updates the screen but it's not clear what exactly is causing it. Any ideas would be great, thanks.

Wrong, it has to do with doing OpenGL calls with no OpenGL context bound. You must call makeCurrent before doing any OpenGL call .

Why does it work in paintGL then? Because Qt makes the context current automatically before calling paintGL , resizeGL and initializeGL (see their documentation).

I don't think @peppe answer correctly because You don't need to call makeCurrent() since Qt have already to

In my opinion, what you really need is just an update() call in mousePressEvent .

If you wan't to call paintGL() to update, what you need is just to call update()

Also, you should know that in glClearColor() , you only set the clearColor attribute on OpenGL state machine. glClear(GL_COLOR_BUFFER_BIT) is the true function which actually clear the color buffer. So you should set clearColor by glClearColor() before calling glClear() .

if I were you, the code would be like:

void GLWidget::mousePressEvent(QMouseEvent *event)
{
    m_lastPos = event->pos();
    r = 1.0f;
    g = 0.0f;
    b = 0.0f;
    a = 1.0f;
    update();
}

void GLWidget::paintGL()
{
    glClearColor(r, g, b, a);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    

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