CopperSpice API  1.9.1
QOpenGLWidget Class Reference

The QOpenGLWidget class is a widget for rendering OpenGL graphics. More...

Inheritance diagram for QOpenGLWidget:
QWidget QObject QPaintDevice

Public Types

enum  UpdateBehavior
 
- Public Types inherited from QWidget
enum  RenderFlag
 
- Public Types inherited from QPaintDevice
enum  PaintDeviceMetric
 

Public Signals

void aboutToCompose ()
 
void aboutToResize ()
 
void frameSwapped ()
 
void resized ()
 
- Public Signals inherited from QWidget
void customContextMenuRequested (const QPoint &pos)
 
void windowIconChanged (const QIcon &icon)
 
void windowIconTextChanged (const QString &iconText)
 
void windowTitleChanged (const QString &title)
 
- Public Signals inherited from QObject
void destroyed (QObject *obj=nullptr)
 
void objectNameChanged (const QString &objectName)
 

Public Methods

 QOpenGLWidget (QWidget *parent=nullptr, Qt::WindowFlags flags=Qt::EmptyFlag)
 
 ~QOpenGLWidget ()
 
QOpenGLContextcontext () const
 
GLuint defaultFramebufferObject () const
 
void doneCurrent ()
 
QSurfaceFormat format () const
 
QImage grabFramebuffer ()
 
bool isValid () const
 
void makeCurrent ()
 
void setFormat (const QSurfaceFormat &format)
 
void setUpdateBehavior (UpdateBehavior updateBehavior)
 
UpdateBehavior updateBehavior () const
 
- Public Methods inherited from QWidget
 QWidget (QWidget *parent=nullptr, Qt::WindowFlags flags=Qt::EmptyFlag)
 
 ~QWidget ()
 
bool acceptDrops () const
 
QString accessibleDescription () const
 
QString accessibleName () const
 
QList< QAction * > actions () const
 
void activateWindow ()
 
void addAction (QAction *action)
 
void addActions (const QList< QAction * > &actions)
 
void adjustSize ()
 
bool autoFillBackground () const
 
QPalette::ColorRole backgroundRole () const
 
QBackingStorebackingStore () const
 
QSize baseSize () const
 
QWidget * childAt (const QPoint &position) const
 
QWidget * childAt (int x, int y) const
 
QRect childrenRect () const
 
QRegion childrenRegion () const
 
void clearFocus ()
 
void clearMask ()
 
QMargins contentsMargins () const
 
QRect contentsRect () const
 
Qt::ContextMenuPolicy contextMenuPolicy () const
 
QCursor cursor () const
 
WId effectiveWinId () const
 
void ensurePolished () const
 
Qt::FocusPolicy focusPolicy () const
 
QWidget * focusProxy () const
 
QWidget * focusWidget () const
 
const QFontfont () const
 
QFontInfo fontInfo () const
 
QFontMetrics fontMetrics () const
 
QPalette::ColorRole foregroundRole () const
 
QRect frameGeometry () const
 
QSize frameSize () const
 
const QRectgeometry () const
 
void getContentsMargins (int *left, int *top, int *right, int *bottom) const
 
QPixmap grab (const QRect &rectangle=QRect (QPoint (0, 0), QSize (-1,-1)))
 
void grabGesture (Qt::GestureType gestureType, Qt::GestureFlags flags=Qt::GestureFlags ())
 
void grabKeyboard ()
 
void grabMouse ()
 
void grabMouse (const QCursor &cursor)
 
int grabShortcut (const QKeySequence &key, Qt::ShortcutContext context=Qt::WindowShortcut)
 
QGraphicsEffectgraphicsEffect () const
 
QGraphicsProxyWidgetgraphicsProxyWidget () const
 
bool hasEditFocus () const
 
bool hasFocus () const
 
virtual bool hasHeightForWidth () const
 
bool hasMouseTracking () const
 
int height () const
 
virtual int heightForWidth (int width) const
 
Qt::InputMethodHints inputMethodHints () const
 
virtual QVariant inputMethodQuery (Qt::InputMethodQuery query) const
 
void insertAction (QAction *before, QAction *action)
 
void insertActions (QAction *before, QList< QAction * > actions)
 
bool isActiveWindow () const
 
bool isAncestorOf (const QWidget *child) const
 
bool isEnabled () const
 
bool isEnabledTo (const QWidget *parent) const
 
bool isEnabledToTLW () const
 
bool isFullScreen () const
 
bool isHidden () const
 
bool isMaximized () const
 
bool isMinimized () const
 
bool isModal () const
 
bool isTopLevel () const
 
bool isVisible () const
 
bool isVisibleTo (const QWidget *parent) const
 
bool isWindow () const
 
bool isWindowModified () const
 
QLayoutlayout () const
 
Qt::LayoutDirection layoutDirection () const
 
QLocale locale () const
 
QPoint mapFrom (const QWidget *parent, const QPoint &pos) const
 
QPoint mapFromGlobal (const QPoint &pos) const
 
QPoint mapFromParent (const QPoint &pos) const
 
QPoint mapTo (const QWidget *parent, const QPoint &pos) const
 
QPoint mapToGlobal (const QPoint &pos) const
 
QPoint mapToParent (const QPoint &pos) const
 
QRegion mask () const
 
int maximumHeight () const
 
QSize maximumSize () const
 
int maximumWidth () const
 
int minimumHeight () const
 
QSize minimumSize () const
 
virtual QSize minimumSizeHint () const
 
int minimumWidth () const
 
void move (const QPoint &point)
 
void move (int x, int y)
 
QWidget * nativeParentWidget () const
 
QWidget * nextInFocusChain () const
 
QRect normalGeometry () const
 
void overrideWindowFlags (Qt::WindowFlags flags)
 
QPaintEnginepaintEngine () const override
 
const QPalettepalette () const
 
QWidget * parentWidget () const
 
QPoint pos () const
 
QWidget * previousInFocusChain () const
 
QRect rect () const
 
void releaseKeyboard ()
 
void releaseMouse ()
 
void releaseShortcut (int id)
 
void removeAction (QAction *action)
 
void render (QPaintDevice *target, const QPoint &targetOffset=QPoint (), const QRegion &sourceRegion=QRegion (), RenderFlags renderFlags=RenderFlags (DrawWindowBackground|DrawChildren))
 
void render (QPainter *painter, const QPoint &targetOffset=QPoint (), const QRegion &sourceRegion=QRegion (), RenderFlags renderFlags=RenderFlags (DrawWindowBackground|DrawChildren))
 
void repaint (const QRect &rect)
 
void repaint (const QRegion &region)
 
void repaint (int x, int y, int w, int h)
 
void resize (const QSize &size)
 
void resize (int w, int h)
 
bool restoreGeometry (const QByteArray &geometry)
 
QByteArray saveGeometry () const
 
void scroll (int dx, int dy)
 
void scroll (int dx, int dy, const QRect &rect)
 
void setAcceptDrops (bool on)
 
void setAccessibleDescription (const QString &description)
 
void setAccessibleName (const QString &name)
 
void setAttribute (Qt::WidgetAttribute attribute, bool enable=true)
 
void setAutoFillBackground (bool enable)
 
void setBackgroundRole (QPalette::ColorRole role)
 
void setBaseSize (const QSize &size)
 
void setBaseSize (int basew, int baseh)
 
void setContentsMargins (const QMargins &margins)
 
void setContentsMargins (int left, int top, int right, int bottom)
 
void setContextMenuPolicy (Qt::ContextMenuPolicy policy)
 
void setCursor (const QCursor &cursor)
 
void setEditFocus (bool enable)
 
void setFixedHeight (int h)
 
void setFixedSize (const QSize &size)
 
void setFixedSize (int w, int h)
 
void setFixedWidth (int w)
 
void setFocus (Qt::FocusReason reason)
 
void setFocusPolicy (Qt::FocusPolicy policy)
 
void setFocusProxy (QWidget *widget)
 
void setFont (const QFont &font)
 
void setForegroundRole (QPalette::ColorRole role)
 
void setGeometry (const QRect &rect)
 
void setGeometry (int x, int y, int w, int h)
 
void setGraphicsEffect (QGraphicsEffect *effect)
 
void setInputMethodHints (Qt::InputMethodHints hints)
 
void setLayout (QLayout *layout)
 
void setLayoutDirection (Qt::LayoutDirection direction)
 
void setLocale (const QLocale &locale)
 
void setMask (const QBitmap &bitmap)
 
void setMask (const QRegion &region)
 
void setMaximumHeight (int maxh)
 
void setMaximumSize (const QSize &size)
 
void setMaximumSize (int maxw, int maxh)
 
void setMaximumWidth (int maxw)
 
void setMinimumHeight (int minh)
 
void setMinimumSize (const QSize &size)
 
void setMinimumSize (int minw, int minh)
 
void setMinimumWidth (int minw)
 
void setMouseTracking (bool enable)
 
void setPalette (const QPalette &palette)
 
void setParent (QWidget *parent)
 
void setParent (QWidget *parent, Qt::WindowFlags flags)
 
void setShortcutAutoRepeat (int id, bool enable=true)
 
void setShortcutEnabled (int id, bool enable=true)
 
void setSizeIncrement (const QSize &size)
 
void setSizeIncrement (int w, int h)
 
void setSizePolicy (QSizePolicy policy)
 
void setSizePolicy (QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
 
void setStatusTip (const QString &data)
 
void setStyle (QStyle *style)
 
void setToolTip (const QString &data)
 
void setToolTipDuration (int msec)
 
void setUpdatesEnabled (bool enable)
 
void setWhatsThis (const QString &str)
 
void setWindowFilePath (const QString &filePath)
 
void setWindowFlags (Qt::WindowFlags flags)
 
void setWindowIcon (const QIcon &icon)
 
void setWindowModality (Qt::WindowModality windowModality)
 
void setWindowOpacity (qreal level)
 
void setWindowRole (const QString &role)
 
void setWindowState (Qt::WindowStates windowState)
 
QSize size () const
 
virtual QSize sizeHint () const
 
QSize sizeIncrement () const
 
QSizePolicy sizePolicy () const
 
void stackUnder (QWidget *widget)
 
QString statusTip () const
 
QStylestyle () const
 
QString styleSheet () const
 
bool testAttribute (Qt::WidgetAttribute attribute) const
 
QString toolTip () const
 
int toolTipDuration () const
 
QWidget * topLevelWidget () const
 
bool underMouse () const
 
void ungrabGesture (Qt::GestureType gestureType)
 
void unsetCursor ()
 
void unsetLayoutDirection ()
 
void unsetLocale ()
 
void update (const QRect &rect)
 
void update (const QRegion &region)
 
void update (int x, int y, int w, int h)
 
void updateGeometry ()
 
bool updatesEnabled () const
 
QRegion visibleRegion () const
 
QString whatsThis () const
 
int width () const
 
QWidget * window () const
 
QString windowFilePath () const
 
Qt::WindowFlags windowFlags () const
 
QWindowwindowHandle () const
 
QIcon windowIcon () const
 
Qt::WindowModality windowModality () const
 
qreal windowOpacity () const
 
QString windowRole () const
 
Qt::WindowStates windowState () const
 
QString windowTitle () const
 
Qt::WindowType windowType () const
 
WId winId () const
 
int x () const
 
int y () const
 
- Public Methods inherited from QObject
 QObject (QObject *parent=nullptr)
 
 ~QObject ()
 
bool blockSignals (bool block)
 
const QList< QObject * > & children () const
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool disconnect (const QObject *receiver, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod, const QString &location, const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod=QString (), const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
void dumpObjectInfo ()
 
void dumpObjectTree ()
 
QList< QStringdynamicPropertyNames () const
 
virtual bool event (QEvent *event)
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 
template<typename T >
findChild (const QString &childName=QString ()) const
 
template<class T >
QList< T > findChildren (const QRegularExpression &regExp, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
template<class T >
QList< T > findChildren (const QString &childName=QString (), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
bool inherits (const QString &className) const
 
void installEventFilter (QObject *filterObj)
 
bool isWidgetType () const
 
bool isWindowType () const
 
void killTimer (int id)
 
const QMetaObjectmetaObject () const
 
void moveToThread (QThread *targetThread)
 
QString objectName () const
 
QObject * parent () const
 
template<class T = QVariant>
property (const QString &name) const
 
void removeEventFilter (QObject *obj)
 
void setObjectName (const QString &name)
 
void setParent (QObject *parent)
 
bool setProperty (const QString &name, const QVariant &value)
 
bool signalsBlocked () const
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 
QThreadthread () const
 
- Public Methods inherited from QPaintDevice
virtual ~QPaintDevice ()
 
int colorCount () const
 
int depth () const
 
int devicePixelRatio () const
 
qreal devicePixelRatioF () const
 
int height () const
 
int heightMM () const
 
int logicalDpiX () const
 
int logicalDpiY () const
 
bool paintingActive () const
 
int physicalDpiX () const
 
int physicalDpiY () const
 
int width () const
 
int widthMM () const
 

Protected Methods

bool event (QEvent *event) override
 
virtual void initializeGL ()
 
int metric (QPaintDevice::PaintDeviceMetric metric) const override
 
QPaintEnginepaintEngine () const override
 
void paintEvent (QPaintEvent *event) override
 
virtual void paintGL ()
 
void resizeEvent (QResizeEvent *event) override
 
virtual void resizeGL (int w, int h)
 
- Protected Methods inherited from QWidget
virtual void actionEvent (QActionEvent *event)
 
virtual void changeEvent (QEvent *event)
 
virtual void closeEvent (QCloseEvent *event)
 
virtual void contextMenuEvent (QContextMenuEvent *event)
 
void create (WId window=0, bool initializeWindow=true, bool destroyOldWindow=true)
 
void destroy (bool destroyWindow=true, bool destroySubWindows=true)
 
virtual void dragEnterEvent (QDragEnterEvent *event)
 
virtual void dragLeaveEvent (QDragLeaveEvent *event)
 
virtual void dragMoveEvent (QDragMoveEvent *event)
 
virtual void dropEvent (QDropEvent *event)
 
virtual void enterEvent (QEvent *event)
 
bool event (QEvent *event) override
 
virtual void focusInEvent (QFocusEvent *event)
 
bool focusNextChild ()
 
virtual bool focusNextPrevChild (bool next)
 
virtual void focusOutEvent (QFocusEvent *event)
 
bool focusPreviousChild ()
 
virtual void hideEvent (QHideEvent *event)
 
void initPainter (QPainter *painter) const override
 
virtual void inputMethodEvent (QInputMethodEvent *event)
 
virtual void keyPressEvent (QKeyEvent *event)
 
virtual void keyReleaseEvent (QKeyEvent *event)
 
virtual void leaveEvent (QEvent *event)
 
int metric (PaintDeviceMetric metric) const override
 
virtual void mouseDoubleClickEvent (QMouseEvent *event)
 
virtual void mouseMoveEvent (QMouseEvent *event)
 
virtual void mousePressEvent (QMouseEvent *event)
 
virtual void mouseReleaseEvent (QMouseEvent *event)
 
virtual void moveEvent (QMoveEvent *event)
 
virtual bool nativeEvent (const QByteArray &eventType, void *message, long *result)
 
virtual void showEvent (QShowEvent *event)
 
virtual void tabletEvent (QTabletEvent *event)
 
virtual void wheelEvent (QWheelEvent *event)
 
- Protected Methods inherited from QObject
virtual void childEvent (QChildEvent *event)
 
virtual void connectNotify (const QMetaMethod &signalMethod) const
 
virtual void customEvent (QEvent *event)
 
virtual void disconnectNotify (const QMetaMethod &signalMethod) const
 
bool isSignalConnected (const QMetaMethod &signalMethod) const
 
int receivers (const QString &signal) const
 
QObject * sender () const
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *event)
 
- Protected Methods inherited from QPaintDevice
 QPaintDevice ()
 

Additional Inherited Members

- Public Typedefs inherited from QWidget
using RenderFlags = QFlags< RenderFlag >
 
- Public Slots inherited from QWidget
bool close ()
 
void hide ()
 
void lower ()
 
void raise ()
 
void repaint ()
 
void setDisabled (bool disable)
 
void setEnabled (bool enable)
 
void setFocus ()
 
void setHidden (bool hidden)
 
void setStyleSheet (const QString &styleSheet)
 
virtual void setVisible (bool visible)
 
void setWindowModified (bool modified)
 
void setWindowTitle (const QString &title)
 
void show ()
 
void showFullScreen ()
 
void showMaximized ()
 
void showMinimized ()
 
void showNormal ()
 
void update ()
 
- Public Slots inherited from QObject
void deleteLater ()
 
- Static Public Methods inherited from QWidget
static QWidget * createWindowContainer (QWindow *window, QWidget *parent=nullptr, Qt::WindowFlags flags=Qt::EmptyFlag)
 
static QWidget * find (WId id)
 
static QWidget * keyboardGrabber ()
 
static QWidget * mouseGrabber ()
 
static void setTabOrder (QWidget *firstWidget, QWidget *secondWidget)
 
- Static Public Methods inherited from QObject
static bool connect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool connect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection, const QString &location=QString ())
 
static bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...), Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotLambda, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, std::nullptr_t, const QObject *receiver, std::nullptr_t)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...))
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, std::nullptr_t slotMethod=nullptr)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotMethod)
 
static QMetaObjectstaticMetaObject ()
 
static QString tr (const char *text, const char *comment=nullptr, std::optional< int > numArg=std::optional< int >())
 
- Protected Slots inherited from QWidget
void updateMicroFocus ()
 
- Properties inherited from QWidget
 acceptDrops
 
 accessibleDescription
 
 accessibleName
 
 autoFillBackground
 
 baseSize
 
 childrenRect
 
 childrenRegion
 
 contextMenuPolicy
 
 cursor
 
 enabled
 
 focus
 
 focusPolicy
 
 font
 
 frameGeometry
 
 frameSize
 
 fullScreen
 
 geometry
 
 height
 
 inputMethodHints
 
 isActiveWindow
 
 layoutDirection
 
 locale
 
 maximized
 
 maximumHeight
 
 maximumSize
 
 maximumWidth
 
 minimized
 
 minimumHeight
 
 minimumSize
 
 minimumSizeHint
 
 minimumWidth
 
 modal
 
 mouseTracking
 
 normalGeometry
 
 palette
 
 pos
 
 rect
 
 size
 
 sizeHint
 
 sizeIncrement
 
 sizePolicy
 
 statusTip
 
 styleSheet
 
 toolTip
 
 updatesEnabled
 
 visible
 
 whatsThis
 
 width
 
 windowFilePath
 
 windowFlags
 
 windowIcon
 
 windowIconText
 
 windowModality
 
 windowModified
 
 windowOpacity
 
 windowTitle
 
 x
 
 y
 
- Properties inherited from QObject
 objectName
 

Detailed Description

The QOpenGLWidget class is a widget for rendering OpenGL graphics.

QOpenGLWidget provides functionality for displaying OpenGL graphics integrated in a CopperSpice application. It is very simple to use: Make your class inherit from it and use the subclass like any other QWidget, except that you have the choice between using QPainter and standard OpenGL rendering commands.

QOpenGLWidget provides three convenient virtual functions you can reimplement in your subclass to perform the typical OpenGL tasks.

paintGL()
Renders the OpenGL scene. Gets called whenever the widget needs to be updated.
resizeGL()
Sets up the OpenGL viewport, projection, etc. Gets called whenever the widget has been resized (and also when it is shown for the first time because all newly created widgets get a resize event automatically).
initializeGL()
Sets up the OpenGL resources and state. Gets called once before the first time resizeGL() or paintGL() is called.

If you need to trigger a repaint from places other than paintGL() call the widget's update() method to schedule an update.

Your widget's OpenGL rendering context is made current when paintGL(), resizeGL(), or initializeGL() is called. If you need to call the standard OpenGL API functions from other places (e.g. in your widget's constructor or in your own paint functions), you must call makeCurrent() first.

All rendering happens into an OpenGL framebuffer object. The method makeCurrent() ensures the frame buffer is bound to the context. When creating and binding additional framebuffer objects in paintGL(), do not re-bind the framebuffer with ID 0. Instead, call defaultFramebufferObject() to get the ID that should be bound.

QOpenGLWidget allows using different OpenGL versions and profiles when the platform supports it. Just set the requested format via setFormat(). Keep in mind however that having multiple QOpenGLWidget instances in the same window requires that they all use the same format, or at least formats that do not make the contexts non-sharable. To overcome this issue, prefer using QSurfaceFormat::setDefaultFormat() instead of setFormat().

Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, Mac OS) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile.

Painting Techniques

As described above, subclass QOpenGLWidget to render pure 3D content in the following way.

  • Reimplement the initializeGL() and resizeGL() methods 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 a QOpenGLWidget subclass using QPainter.

  • In paintGL() instead of issuing OpenGL commands, construct a QPainter object for use on the widget.
  • Draw primitives using QPainter methods.
  • 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 using QPainter only, it is also possible to perform the painting like it is done for ordinary widgets by reimplementing paintEvent().

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

OpenGL Function Calls

When making OpenGL function calls, it is strongly recommended to avoid calling the functions directly. Instead, prefer using QOpenGLFunctions (when making portable applications) or the versioned variants (for example, QOpenGLFunctions_3_2_Core and similar, when targeting modern, desktop-only OpenGL). This way the application will work correctly in all build configurations, including the ones that perform dynamic OpenGL implementation loading which means applications are not directly linking to an GL implementation and thus direct function calls are not feasible.

In paintGL() the current context is always accessible by calling QOpenGLContext::currentContext(). From this context an already initialized, ready-to-be-used QOpenGLFunctions instance is retrievable by calling QOpenGLContext::functions(). An alternative to prefixing every GL call is to inherit from QOpenGLFunctions and call QOpenGLFunctions::initializeOpenGLFunctions() in initializeGL().

As for the OpenGL headers, note that in most cases there will be no need to directly include any headers like GL.h. The OpenGL-related CopperSpice headers will include qopengl.h which will in turn include an appropriate header for the system. This might be an OpenGL ES 3.x or 2.0 header, the highest version that is available, or a system-provided gl.h. In addition, a copy of the extension headers (called glext.h on some systems) is provided as part of CopperSpice both for OpenGL and OpenGL ES. These will get included automatically on platforms where feasible. This means that constants and function pointer typedefs from ARB, EXT, OES extensions are automatically available.

Member Enumeration Documentation

This enum describes the update semantics of QOpenGLWidget.

Constant Value Description
QOpenGLWidget::NoPartialUpdate 0

QOpenGLWidget will discard the contents of the color buffer and the ancillary buffers after the QOpenGLWidget is rendered to screen. This is the same behavior that can be expected by calling QOpenGLContext::swapBuffers with a default opengl enabled QWindow as the argument. This enum value can have some performance benefits on certain hardware architectures common in the mobile and embedded space when a framebuffer object is used as the rendering target. The framebuffer object is invalidated between frames with glDiscardFramebufferEXT or a glClear.

Refer to the documentation of EXT_discard_framebuffer for more information.
https://www.khronos.org/registry/gles/extensions/EXT/EXT_discard_framebuffer.txt

QOpenGLWidget::PartialUpdate 1 The framebuffer objects color buffer and ancillary buffers are not invalidated between frames.
See also
updateBehavior(), setUpdateBehavior()

Constructor & Destructor Documentation

QOpenGLWidget::QOpenGLWidget ( QWidget parent = nullptr,
Qt::WindowFlags  flags = Qt::EmptyFlag 
)
explicit

Constructs a widget which is a child of parent with widget flags set to flags.

QOpenGLWidget::~QOpenGLWidget ( )

Destroys the QOpenGLWidget instance, freeing its resources.

The QOpenGLWidget's context is made current in the destructor, allowing for safe destruction of any child object that may need to release OpenGL resources belonging to the context provided by this widget.

If you have objects wrapping OpenGL resources (such as QOpenGLBuffer, QOpenGLShaderProgram, etc.) as members of a OpenGLWidget subclass, you may need to add a call to makeCurrent() in that subclass destructor as well. Due to the rules of C++ object destruction, those objects will be destroyed before calling this function (but after that the destructor of the subclass has run), therefore making the OpenGL context current in this function happens too late for their safe disposal.

See also
makeCurrent()

Method Documentation

void QOpenGLWidget::aboutToCompose ( )
signal

This signal is emitted when the widget's top-level window is about to begin composing the textures of its QOpenGLWidget children and the other widgets.

void QOpenGLWidget::aboutToResize ( )
signal

This signal is emitted when the widget's size is changed and therefore the framebuffer object is going to be recreated.

QOpenGLContext * QOpenGLWidget::context ( ) const

Returns the QOpenGLContext used by this widget or a nullptr if not initialized. The context and the framebuffer object used by the widget changes when reparenting the widget via setParent().

See also
QOpenGLContext::setShareContext(), defaultFramebufferObject()
GLuint QOpenGLWidget::defaultFramebufferObject ( ) const

Returns The framebuffer object handle or 0 if not yet initialized.

The framebuffer object belongs to the context returned by context() and may not be accessible from other contexts. The context and the framebuffer object used by the widget changes when reparenting the widget via setParent(). In addition, the framebuffer object changes on each resize.

See also
context()
void QOpenGLWidget::doneCurrent ( )

Releases the context. It is not necessary to call this method in most cases since the widget will make sure the context is bound and released properly when invoking paintGL().

bool QOpenGLWidget::event ( QEvent event)
overrideprotected

Reimplemented from QWidget::event()

QSurfaceFormat QOpenGLWidget::format ( ) const

Returns the context and surface format used by this widget and its toplevel window. After the widget and its toplevel have both been created, resized and shown, this function will return the actual format of the context. This may differ from the requested format if the request could not be fulfilled by the platform. It is also possible to get larger color buffer sizes than requested.

When the widget's window and the related OpenGL resources are not yet initialized, the return value is the format that has been set via setFormat().

See also
setFormat(), context()
void QOpenGLWidget::frameSwapped ( )
signal

This signal is emitted after the widget's top-level window has finished composition and returned from its potentially blocking QOpenGLContext::swapBuffers() call.

QImage QOpenGLWidget::grabFramebuffer ( )

Renders and returns a 32-bit RGB image of the framebuffer. This is a potentially expensive operation because it relies on glReadPixels() to read back the pixels. This may be slow and can stall the GPU pipeline.

void QOpenGLWidget::initializeGL ( )
protectedvirtual

Called once before the first call to paintGL() or resizeGL(). Reimplement it in a subclass. This fmethod should set up any required OpenGL resources and state.

There is no need to call makeCurrent() because this has already been done when this function is called. Note however that the framebuffer is not yet available at this stage, so avoid issuing draw calls from here. Defer such calls to paintGL() instead.

See also
paintGL(), resizeGL()
bool QOpenGLWidget::isValid ( ) const

Returns true if the widget and OpenGL resources, like the context, have been successfully initialized. The return value is always false until the widget is shown.

void QOpenGLWidget::makeCurrent ( )

Prepares for rendering OpenGL content for this widget by making the corresponding context current and binding the framebuffer object in that context. It is not necessary to call this function in most cases, because it is called automatically before invoking paintGL().

See also
context(), paintGL(), doneCurrent()
int QOpenGLWidget::metric ( QPaintDevice::PaintDeviceMetric  metric) const
overrideprotectedvirtual

Returns the metric information for the given paint device metric.

See also
PaintDeviceMetric

Reimplemented from QPaintDevice::metric()

QPaintEngine* QOpenGLWidget::paintEngine ( ) const
overrideprotectedvirtual

Returns a pointer to the paint engine used for drawing on the device.

Implements QPaintDevice::paintEngine()

void QOpenGLWidget::paintEvent ( QPaintEvent event)
overrideprotectedvirtual

This event handler can be reimplemented in a subclass to receive paint events passed in event. A paint event is a request to repaint all or part of a widget. It can happen for one of the following reasons.

  • repaint() or update() was invoked
  • widget was obscured and has now been uncovered
  • some other reason

Many widgets can simply repaint their entire surface when asked to, but some slow widgets need to optimize by painting only the requested region: QPaintEvent::region(). This speed optimization does not change the result, as painting is clipped to that region during event processing. QListView and QTableView do this, for example.

CopperSpice also tries to speed up painting by merging multiple paint events into one. When update() is called several times or the window system sends several paint events, CopperSpice merges these events into one event with a larger region (see QRegion::united()). The repaint() method does not permit this optimization, so we suggest using update() whenever possible.

When the paint event occurs, the update region has normally been erased, so you are painting on the widget's background. The background can be set using setBackgroundRole() and setPalette().

QWidget automatically double-buffers its painting, so there is no need to write double-buffering code in paintEvent() to avoid flicker.

For the X11 platform it is possible to toggle global double buffering by calling qt_x11_set_global_double_buffer().

extern void qt_x11_set_global_double_buffer(bool);
qt_x11_set_global_double_buffer(false);

Generally you should refrain from calling update() or repaint() inside a paintEvent(). For example, calling update() or repaint() on children inside a paintevent() results in undefined behavior; the child may or may not get a paint event.

Warning
If you are using a custom paint engine without the CopperSpice backingstore, Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will never be called; the backingstore will be used instead.
See also
event(), repaint(), update(), QPainter, QPixmap, QPaintEvent

Reimplemented from QWidget::paintEvent()

void QOpenGLWidget::paintGL ( )
protectedvirtual

Called whenever the widget needs to be painted. Reimplement it in a subclass. There is no need to call makeCurrent() because this has already been done when this method is called.

Before invoking this function, the context and the framebuffer are bound, and the viewport is set up by a call to glViewport(). No other state is set and no clearing or drawing is performed by the framework.

See also
initializeGL(), resizeGL()
void QOpenGLWidget::resized ( )
signal

This signal is emitted right after the framebuffer object has been recreated due to resizing the widget.

void QOpenGLWidget::resizeEvent ( QResizeEvent event)
overrideprotectedvirtual

This event handler can be reimplemented in a subclass to receive widget resize events which are passed in the event parameter. When resizeEvent() is called, the widget already has its new geometry. The old size is accessible through QResizeEvent::oldSize().

The widget will be erased and receive a paint event immediately after processing the resize event. No drawing need be (or should be) done inside this handler.

See also
moveEvent(), event(), resize(), QResizeEvent, paintEvent()

Reimplemented from QWidget::resizeEvent()

void QOpenGLWidget::resizeGL ( int  w,
int  h 
)
protectedvirtual

Called any time the widget has been resized. The new size is specified by w and h. There is no need to call makeCurrent() because this has already been done when this function is called. Additionally, the framebuffer is also bound.

See also
initializeGL(), paintGL()
void QOpenGLWidget::setFormat ( const QSurfaceFormat format)

Sets the requested surface format.

When the format is not explicitly set via this function, the format returned by QSurfaceFormat::defaultFormat() will be used. This means that when having multiple OpenGL widgets, individual calls to this function can be replaced by one single call to QSurfaceFormat::setDefaultFormat() before creating the first widget.

Requesting an alpha buffer via this function will not lead to the desired results when the intention is to make other widgets beneath visible. Instead, use Qt::WA_AlwaysStackOnTop to enable semi-transparent QOpenGLWidget instances with other widgets visible underneath. Keep in mind however that this breaks the stacking order, so it will no longer be possible to have other widgets on top of the QOpenGLWidget.

See also
format(), Qt::WidgetAttribute, QSurfaceFormat::setDefaultFormat()
void QOpenGLWidget::setUpdateBehavior ( QOpenGLWidget::UpdateBehavior  updateBehavior)

Sets this widget's update behavior to updateBehavior.

See also
updateBehavior()
QOpenGLWidget::UpdateBehavior QOpenGLWidget::updateBehavior ( ) const

Returns the update behavior of the widget.

See also
setUpdateBehavior()