Search code examples
qtopenglglreadpixels

glReadPixels seems to read at the wrong coordinates in Qt


I'm trying to develop an application using OpenGL 4.0 and Qt 5.3 and I want to implement color picking to select different models in a QGLWidget. So basically, when I detect a mouse click, I:

  1. Get the position of the mouse
  2. Render the scene
    1. Set a white background (glClearColor then glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    2. I bind my shader program
    3. I draw my models (each one with a different color and its own transformation matrix)
    4. Release my shader program
  3. Call glFlush and glFinish to make sure I have finished rendering before calling glReadPixels
  4. Call glReadPixels(mouse.x, window_height - mouse.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, data) data being a GLubyte array of length 4

My program runs "well" but when I want to select an object, I have to click a little more up and right than where the model really is. I tried to swap buffers to check if the models are rendered at the right position and yes, they are... I also tried to call glPixelStorei(GL_PACK_ALIGNMENT, x) with x = 1, 2, 4, 8 before glReadPixels but it doesn't seem to affect it.


Solution

  • Thanks for your comments Michael IV and jozxyqk. In the end I just ended up drawing in a QOpenGLFramebufferObject and I read the pixels color using a QImage. Like this:

    QImage image = fbo->toImage(); //fbo is the QOpenGLFramebufferObject
    QRgb rgb = image.pixel(mouse.x(), mouse.y());
    

    For more information, see: http://dangelog.wordpress.com/2013/02/10/using-fbos-instead-of-pbuffers-in-qt-5-2/

    Happy coding!