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:
glClearColor
then glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glFlush
and glFinish
to make sure I have finished rendering before calling glReadPixels
glReadPixels(mouse.x, window_height - mouse.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, data)
data being a GLubyte
array of length 4My 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.
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!