QOpenGLWidget绘制2D的方法

时间:2023-02-07 23:24:18

可以重新实现paintGL(),在其中通过QPainter绘图。通过update()重绘。

也可以使用通常QWidget的paintEvent()方法实现绘图,通过update()重绘。

下面是官方文档的节选:

Painting Techniques

As described above, subclassQOpenGLWidget to render pure 3D content in the following way:

  • Reimplement the initializeGL() andresizeGL() functions to set up the OpenGL state and provide a perspective transformation.
  • Reimplement paintGL() to paint the 3D scene, calling only OpenGL functions.

It is also possible to draw 2D graphics onto aQOpenGLWidget subclass usingQPainter:

  • In paintGL(), instead of issuing OpenGL commands, construct aQPainter object for use on the widget.
  • Draw primitives using QPainter's member functions.
  • Direct OpenGL commands can still be issued. However, you must make sure these are enclosed by a call to the painter's beginNativePainting() and endNativePainting().

When performing drawing usingQPainter only, it is also possible to perform the painting like it is done for ordinary widgets: by reimplementingpaintEvent().

  • Reimplement the paintEvent() function.
  • Construct a QPainter object targeting the widget. Either pass the widget to the constructor or theQPainter::begin() function.
  • Draw primitives using QPainter's member functions.
  • Painting finishes then the QPainter instance is destroyed. Alternatively, callQPainter::end() explicitly.