QOpenGLWidget and QPainter
-
Hi, I want to draw some 2D grath on my qopenglwidget by qpainter. But I don not know how to blend opengl and qpainter. And I've made some attempts. 2D and 3D can be displayed individually, not together. Override the paintEvent()? Or glPushAttrib(GL_ALL_ATTRIB_BITS) and glPopAttrib()?
I have some confusion. How should I modify the code?
Thanks in advance.
Qt Creator 5.9.1 on windows 10.void my_OpenGL::paintGL() { float currentFrame = glutGet(GLUT_ELAPSED_TIME); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; const qreal retinaScale = devicePixelRatio(); glViewport(0, 0, width() * retinaScale, height() * retinaScale); QPainter ptr(this); ptr.beginNativePainting(); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); /******3D.begin*******/ m_program->bind(); glBindVertexArray(VAO); m_program->setUniformValue(m_program->uniformLocation("projection"), projection); m_program->setUniformValue(m_program->uniformLocation("view"), view); m_program->setUniformValue(m_program->uniformLocation("model"), model); m_program->setUniformValue(m_program->uniformLocation("color"), QVector3D(190.0, 190.0, 190.0)); glDrawElements(GL_TRIANGLES, elementVector.count()*3, GL_UNSIGNED_INT, 0); m_program->setUniformValue(m_program->uniformLocation("color"), QVector3D(0.0, 0.0, 0.0)); glDrawElements(GL_LINES, elementVector.size()*3, GL_UNSIGNED_INT, 0); m_program->release(); /******3D.end*******/ ptr.endNativePainting(); ptr.fillRect(QRect(geometry().x(), geometry().y(), width(), height()), backgroundBrush); update(); }
-
-
Thank you for your reply.
Yes, I have noticed this example. But it just tell us how to draw 2D graphics primitives onto paint devices. I have learned it. And now I want to know how to draw 3D graphics on the basis of the 2D graphics background. For instance, I want to add a background of a gradual color for my 3D graphics. -
I may have misunderstood your goals.
Can you give an example/screenshot of what you are trying to do ?
-
Just like this. My idea is drawing the blade by OpenGL, and the others by QPainter, including the text, the background, the color bar and the scale. Now I can draw it individually, but fail to combine together. -
From the looks of it, you might want to consider QtQuick for the UI part. Could prove easier.
-
You seem to be on the right path. But if you're using QPainter::fillRect() to paint the background, you'd want to do it BEFORE your OpenGL 3D painting code, not after. Otherwise fillRect() would wipe out all your 3D painting.
It's OK to mix QPainter and OpenGL painting in QOpenGLWidget::paintGL() in any order, as long as OpenGL parts are enclosed by beginNativePainting() and endNativePainting(). You can do 1) QPainter::fillRect() background 2) OpenGL 3D 3) more QPainter painting for other 2D objects over the background.
-
I have a similar thread with no responses to it. Please can you let me know how this problem was fixed. My thread: Rendering 2D with QPainter and QOpenGLWidget