CopperSpice API  1.7.2
QGLWidget Class Reference

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

Inheritance diagram for QGLWidget:
QWidget QObject QPaintDevice

Public Slots

virtual void updateGL ()
 
virtual void updateOverlayGL ()
 
- 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 ()
 

Public Methods

 QGLWidget (const QGLFormat &format, QWidget *parent=nullptr, const QGLWidget *shareWidget=nullptr, Qt::WindowFlags f=Qt::WindowFlags ())
 
 QGLWidget (QGLContext *context, QWidget *parent=nullptr, const QGLWidget *shareWidget=nullptr, Qt::WindowFlags f=Qt::WindowFlags ())
 
 QGLWidget (QWidget *parent=nullptr, const QGLWidget *shareWidget=nullptr, Qt::WindowFlags f=Qt::WindowFlags ())
 
 ~QGLWidget ()
 
GLuint bindTexture (const QImage &image, GLenum target, GLint format, QGLContext::BindOptions options)
 
GLuint bindTexture (const QImage &image, GLenum target=GL_TEXTURE_2D, GLint format=GL_RGBA)
 
GLuint bindTexture (const QPixmap &pixmap, GLenum target, GLint format, QGLContext::BindOptions options)
 
GLuint bindTexture (const QPixmap &pixmap, GLenum target=GL_TEXTURE_2D, GLint format=GL_RGBA)
 
GLuint bindTexture (const QString &fileName)
 
const QGLColormapcolormap () const
 
QGLContextcontext () const
 
void deleteTexture (GLuint tx_id)
 
void doneCurrent ()
 
bool doubleBuffer () const
 
void drawTexture (const QPointF &point, GLuint textureId, GLenum textureTarget=GL_TEXTURE_2D)
 
void drawTexture (const QRectF &target, GLuint textureId, GLenum textureTarget=GL_TEXTURE_2D)
 
QGLFormat format () const
 
QImage grabFrameBuffer (bool withAlpha=false)
 
bool isSharing () const
 
bool isValid () const
 
void makeCurrent ()
 
void makeOverlayCurrent ()
 
const QGLContextoverlayContext () const
 
QPaintEnginepaintEngine () const override
 
void qglClearColor (const QColor &c) const
 
void qglColor (const QColor &c) const
 
QPixmap renderPixmap (int w=0, int h=0, bool useContext=false)
 
void renderText (double x, double y, double z, const QString &str, const QFont &fnt=QFont ())
 
void renderText (int x, int y, const QString &str, const QFont &fnt=QFont ())
 
void setColormap (const QGLColormap &map)
 
void setFormat (const QGLFormat &format)
 
void swapBuffers ()
 
- 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)
 
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 &objName=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
 

Static Public Methods

static QImage convertToGLFormat (const QImage &img)
 
- 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)
 
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 Methods

bool autoBufferSwap () const
 
bool event (QEvent *) override
 
virtual void glDraw ()
 
virtual void glInit ()
 
virtual void initializeGL ()
 
virtual void initializeOverlayGL ()
 
void paintEvent (QPaintEvent *) override
 
virtual void paintGL ()
 
virtual void paintOverlayGL ()
 
void resizeEvent (QResizeEvent *) override
 
virtual void resizeGL (int w, int h)
 
virtual void resizeOverlayGL (int w, int h)
 
void setAutoBufferSwap (bool on)
 
- 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 ()
 

Friends

class QGLContext
 
class QGLPixelBuffer
 

Additional Inherited Members

- Public Types inherited from QWidget
enum  RenderFlag
 
- Public Types inherited from QPaintDevice
enum  PaintDeviceMetric
 
- 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)
 
- 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 QGLWidget class is a widget for rendering OpenGL graphics.

QGLWidget provides functionality for displaying OpenGL graphics integrated into a CopperSpice application. It is very simple to use. You 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.

QGLWidget provides three convenient virtual functions that 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 rendering context, defines display lists, etc. Gets called once before the first time resizeGL() or paintGL() is called.

The following is an example of how a QGLWidget subclass might look.

class MyGLDrawer : public QGLWidget
{
CS_OBJECT(MyGLDrawer)
public:
MyGLDrawer(QWidget *parent)
protected:
void initializeGL()
{
// Set up the rendering context, define display lists etc.:
...
glClearColor(0.0, 0.0, 0.0, 0.0);
glEnable(GL_DEPTH_TEST);
...
}
void resizeGL(int w, int h)
{
// setup viewport, projection etc.:
glViewport(0, 0, (GLint)w, (GLint)h);
...
glFrustum(...);
...
}
void paintGL()
{
// draw the scene:
...
glRotatef(...);
glMaterialfv(...);
glBegin(GL_QUADS);
glVertex3f(...);
glVertex3f(...);
...
glEnd();
...
}
};

If you need to trigger a repaint from places other than paintGL() (a typical example is when using timers to animate scenes), you should call the widget's updateGL() function.

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.

QGLWidget provides functions for requesting a new display format and you can also create widgets with customized rendering contexts.

You can also share OpenGL display lists between QGLWidget objects (see the documentation of the QGLWidget constructors for details).

Note that under Windows, the QGLContext belonging to a QGLWidget has to be recreated when the QGLWidget is reparented. This is necessary due to limitations on the Windows platform. This will most likely cause problems for users that have subclassed and installed their own QGLContext on a QGLWidget. It is possible to work around this issue by putting the QGLWidget inside a dummy widget and then reparenting the dummy widget, instead of the QGLWidget. This will side-step the issue altogether, and is what we recommend for users that need this kind of functionality.

On Max OS X, when CopperSpice is built with Cocoa support, a QGLWidget ca not have any sibling widgets placed ontop of itself. This is due to limitations in the Cocoa API and is not supported by Apple.

Overlays

The QGLWidget creates a GL overlay context in addition to the normal context if overlays are supported by the underlying system.

If you want to use overlays, you specify it in the format. (Note: Overlay must be requested in the format passed to the QGLWidget constructor.) Your GL widget should also implement some or all of these virtual methods:

These methods work in the same way as the normal paintGL() etc. functions, except that they will be called when the overlay context is made current. You can explicitly make the overlay context current by using makeOverlayCurrent(), and you can access the overlay context directly (e.g. to ask for its transparent color) by calling overlayContext().

On X servers in which the default visual is in an overlay plane, non-GL CopperSpice windows can also be used for overlays.

Painting Techniques

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

It is also possible to draw 2D graphics onto a QGLWidget subclass, it is necessary to reimplement QGLWidget::paintEvent() and do the following:

Painting 2D content on top of 3D content takes a little more effort.

Threading

Support for doing threaded GL rendering has been improved. There are three scenarios that we currently support:

  • 1. Buffer swapping in a thread.Swapping buffers in a double buffered context may be a synchronous, locking call that may be a costly operation in some GL implementations. Especially so on embedded devices. It's not optimal to have the CPU idling while the GPU is doing a buffer swap. In those cases it is possible to do the rendering in the main thread and do the actual buffer swap in a separate thread. This can be done with the following steps:

    1. Call doneCurrent() in the main thread when the rendering is finished.
    2. Notify the swapping thread that it can grab the context.
    3. Make the rendering context current in the swapping thread with makeCurrent() and then call swapBuffers().
    4. Call doneCurrent() in the swapping thread and notify the main thread that swapping is done.

    Doing this will free up the main thread so that it can continue with, for example, handling UI events or network requests. Even if there is a context swap involved, it may be preferable compared to having the main thread wait while the GPU finishes the swap operation. Note that this is highly implementation dependent.

  • 2. Texture uploading in a thread.Doing texture uploads in a thread may be very useful for applications handling large amounts of images that needs to be displayed, like for instance a photo gallery application. This is supported in CopperSpice through the existing bindTexture() API. A simple way of doing this is to create two sharing QGLWidgets. One is made current in the main GUI thread, while the other is made current in the texture upload thread. The widget in the uploading thread is never shown, it is only used for sharing textures with the main thread. For each texture that is bound via bindTexture(), notify the main thread so that it can start using the texture.
  • 3. Using QPainter to draw into a QGLWidget in a thread. It is possible to draw into a QGLWidget using a QPainter in a separate thread. Note that this is also possible for QGLPixelBuffers and QGLFramebufferObjects. Since this is only supported in the GL 2 paint engine, OpenGL 2.0 or OpenGL ES 2.0 is required.

    QGLWidgets can only be created in the main GUI thread. This means a call to doneCurrent() is necessary to release the GL context from the main thread, before the widget can be drawn into by another thread. Also, the main GUI thread will dispatch resize and paint events to a QGLWidget when the widget is resized, or parts of it becomes exposed or needs redrawing. It is therefore necessary to handle those events because the default implementations inside QGLWidget will try to make the QGLWidget's context current, which again will interfere with any threads rendering into the widget. Reimplement QGLWidget::paintEvent() and QGLWidget::resizeEvent() to notify the rendering thread that a resize or update is necessary, and be careful not to call the base class implementation. If you are rendering an animation, it might not be necessary to handle the paint event at all since the rendering thread is doing regular updates. Then it would be enough to reimplement QGLWidget::paintEvent() to do nothing.

As a general rule when doing threaded rendering: be aware that binding and releasing contexts in different threads have to be synchronized by the user. A GL rendering context can only be current in one thread at any time. If you try to open a QPainter on a QGLWidget and the widget's rendering context is current in another thread, it will fail.

Note that under X11 it is necessary to set the Qt::AA_X11InitThreads application attribute to make the X11 library and GLX calls thread safe, otherwise the above scenarios will fail.

In addition to this, rendering using raw GL calls in a separate thread is supported.

OpenGL is a trademark of Silicon Graphics, Inc. in the United States and other countries.

See also
QGLPixelBuffer

Constructor & Destructor Documentation

QGLWidget::QGLWidget ( QWidget parent = nullptr,
const QGLWidget *  shareWidget = nullptr,
Qt::WindowFlags  f = Qt::WindowFlags() 
)
explicit

Constructs an OpenGL widget with a parent widget.

The default format is used. The widget will be invalid if the system has no OpenGL support.

The parent and widget flag, f, arguments are passed to the QWidget constructor.

If shareWidget is a valid QGLWidget, this widget will share OpenGL display lists and texture objects with shareWidget. But if shareWidget and this widget have different formats, sharing might not be possible. You can check whether sharing is in effect by calling isSharing().

The initialization of OpenGL rendering state, etc. should be done by overriding the initializeGL() function, rather than in the constructor of your QGLWidget subclass.

See also
QGLFormat::defaultFormat()
QGLWidget::QGLWidget ( QGLContext context,
QWidget parent = nullptr,
const QGLWidget *  shareWidget = nullptr,
Qt::WindowFlags  f = Qt::WindowFlags() 
)
explicit

Constructs an OpenGL widget with parent parent.

The context argument is a pointer to the QGLContext that you wish to be bound to this widget. This allows you to pass in your own QGLContext sub-classes.

The widget will be invalid if the system has no OpenGL support.

The parent and widget flag, f, arguments are passed to the QWidget constructor.

If shareWidget is a valid QGLWidget, this widget will share OpenGL display lists and texture objects with shareWidget. But if shareWidget and this widget have different formats, sharing might not be possible. You can check whether sharing is in effect by calling isSharing().

The initialization of OpenGL rendering state, etc. should be done by overriding the initializeGL() function, rather than in the constructor of your QGLWidget subclass.

See also
QGLFormat::defaultFormat(), isValid()
QGLWidget::QGLWidget ( const QGLFormat format,
QWidget parent = nullptr,
const QGLWidget *  shareWidget = nullptr,
Qt::WindowFlags  f = Qt::WindowFlags() 
)
explicit

Constructs an OpenGL widget with parent parent.

The format argument specifies the desired rendering options. If the underlying OpenGL/Window system can not satisfy all the features requested in format, the nearest subset of features will be used. After creation, the format() method will return the actual format obtained.

The widget will be invalid if the system has no OpenGL support.

The parent and widget flag, f, arguments are passed to the QWidget constructor.

If shareWidget is a valid QGLWidget, this widget will share OpenGL display lists and texture objects with shareWidget. But if shareWidget and this widget have different formats, sharing might not be possible. You can check whether sharing is in effect by calling isSharing().

The initialization of OpenGL rendering state, etc. should be done by overriding the initializeGL() function, rather than in the constructor of your QGLWidget subclass.

See also
QGLFormat::defaultFormat(), isValid()
QGLWidget::~QGLWidget ( )

Destroys the widget.

Method Documentation

bool QGLWidget::autoBufferSwap ( ) const
protected

Returns true if the widget is doing automatic GL buffer swapping, otherwise returns false.

See also
setAutoBufferSwap()
GLuint QGLWidget::bindTexture ( const QImage image,
GLenum  target,
GLint  format,
QGLContext::BindOptions  options 
)

This is an overloaded function.

The binding options are a set of options used to decide how to bind the texture to the context.

GLuint QGLWidget::bindTexture ( const QImage image,
GLenum  target = GL_TEXTURE_2D,
GLint  format = GL_RGBA 
)

Calls QGLContext::bindTexture(image, target, format) on the currently set context.

See also
deleteTexture()
GLuint QGLWidget::bindTexture ( const QPixmap pixmap,
GLenum  target,
GLint  format,
QGLContext::BindOptions  options 
)

This is an overloaded function.

Generates and binds a 2D GL texture to the current context, based on pixmap. The generated texture id is returned and can be used in

The binding options are a set of options used to decide how to bind the texture to the context.

GLuint QGLWidget::bindTexture ( const QPixmap pixmap,
GLenum  target = GL_TEXTURE_2D,
GLint  format = GL_RGBA 
)

Calls QGLContext::bindTexture(pixmap, target, format) on the currently set context.

See also
deleteTexture()
GLuint QGLWidget::bindTexture ( const QString fileName)

This is an overloaded function.

Calls QGLContext::bindTexture(fileName) on the currently set context.

See also
deleteTexture()
const QGLColormap & QGLWidget::colormap ( ) const

Returns the colormap for this widget.

Usually it is only top-level widgets that can have different colormaps installed. Asking for the colormap of a child widget will return the colormap for the child's top-level widget.

If no colormap has been set for this widget, the QGLColormap returned will be empty.

See also
setColormap(), QGLColormap::isEmpty()
QGLContext * QGLWidget::context ( ) const

Returns the context of this widget.

It is possible that the context is not valid (see isValid()), for example, if the underlying hardware does not support the format attributes that were requested.

QImage QGLWidget::convertToGLFormat ( const QImage img)
static

Converts the image img into the unnamed format expected by OpenGL functions such as glTexImage2D(). The returned image is not usable as a QImage, but QImage::width(), QImage::height() and QImage::bits() may be used with OpenGL. The GL format used is GL_RGBA.

void QGLWidget::deleteTexture ( GLuint  id)

Calls QGLContext::deleteTexture(id) on the currently set context.

See also
bindTexture()
void QGLWidget::doneCurrent ( )

Makes no GL context the current context. Normally, you do not need to call this function; QGLContext calls it as necessary. However, it may be useful in multithreaded environments.

bool QGLWidget::doubleBuffer ( ) const

Returns true if the contained GL rendering context has double buffering, otherwise returns false.

See also
QGLFormat::doubleBuffer()
void QGLWidget::drawTexture ( const QPointF point,
GLuint  textureId,
GLenum  textureTarget = GL_TEXTURE_2D 
)

Calls the corresponding QGLContext::drawTexture() with point, textureId, and textureTarget for this widget's context.

void QGLWidget::drawTexture ( const QRectF target,
GLuint  textureId,
GLenum  textureTarget = GL_TEXTURE_2D 
)

Calls the corresponding QGLContext::drawTexture() with target, textureId, and textureTarget for this widget's context.

bool QGLWidget::event ( QEvent event)
overrideprotected

Reimplemented from QObject::event().

QGLFormat QGLWidget::format ( ) const

Returns the format of the contained GL rendering context.

See also
setFormat()
void QGLWidget::glDraw ( )
protectedvirtual

Executes the virtual function paintGL().

The widget's rendering context will become the current context and initializeGL() will be called if it has not already been called.

void QGLWidget::glInit ( )
protectedvirtual

Initializes OpenGL for this widget's context. Calls the virtual function initializeGL().

QImage QGLWidget::grabFrameBuffer ( bool  withAlpha = false)

Returns an image of the frame buffer. If withAlpha is true the alpha channel is included.

Depending on your hardware, you can explicitly select which color buffer to grab with a glReadBuffer() call before calling this function.

void QGLWidget::initializeGL ( )
protectedvirtual

This virtual function is called once before the first call to paintGL() or resizeGL(), and then once whenever the widget has been assigned a new QGLContext. Reimplement it in a subclass.

This function should set up any required OpenGL context rendering flags, defining display lists, etc.

There is no need to call makeCurrent() because this has already been done when this function is called.

void QGLWidget::initializeOverlayGL ( )
protectedvirtual

This virtual function is used in the same manner as initializeGL() except that it operates on the widget's overlay context instead of the widget's main context. This means that initializeOverlayGL() is called once before the first call to paintOverlayGL() or resizeOverlayGL(). Reimplement it in a subclass.

This function should set up any required OpenGL context rendering flags, defining display lists, etc. for the overlay context.

There is no need to call makeOverlayCurrent() because this has already been done when this function is called.

bool QGLWidget::isSharing ( ) const

Returns true if this widget's GL context is shared with another GL context, otherwise false is returned. Context sharing might not be possible if the widgets use different formats.

See also
format()
bool QGLWidget::isValid ( ) const

Returns true if the widget has a valid GL rendering context, otherwise returns false. A widget will be invalid if the system has no OpenGL support.

void QGLWidget::makeCurrent ( )

Makes this widget the current widget for OpenGL operations, i.e. makes the widget's rendering context the current OpenGL rendering context.

void QGLWidget::makeOverlayCurrent ( )

Makes the overlay context of this widget current. Use this if you need to issue OpenGL commands to the overlay context outside of initializeOverlayGL(), resizeOverlayGL(), and paintOverlayGL().

Does nothing if this widget has no overlay.

See also
makeCurrent()
const QGLContext * QGLWidget::overlayContext ( ) const

Returns the overlay context of this widget, or 0 if this widget has no overlay.

See also
context()
QPaintEngine* QGLWidget::paintEngine ( ) const
overridevirtual

Returns the widget's paint engine.

This method should not be called explicitly by the user, since it is meant for reimplementation purposes only. The method is called by CopperSpice internally, and the default implementation may not always return a valid pointer.

Reimplemented from QWidget.

void QGLWidget::paintEvent ( QPaintEvent event)
overrideprotectedvirtual

Reimplemented from QWidget::paintEvent().

Handles paint events passed in the event parameter. Will cause the virtual paintGL() function to be called.

The widget's rendering context will become the current context and initializeGL() will be called if it has not already been called.

Reimplemented from QWidget.

void QGLWidget::paintGL ( )
protectedvirtual

This virtual function is 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 function is called.

void QGLWidget::paintOverlayGL ( )
protectedvirtual

This virtual function is used in the same manner as paintGL() except that it operates on the widget's overlay context instead of the widget's main context. This means that paintOverlayGL() is called whenever the widget's overlay needs to be painted. Reimplement it in a subclass.

There is no need to call makeOverlayCurrent() because this has already been done when this function is called.

void QGLWidget::qglClearColor ( const QColor c) const

Convenience function for specifying the clearing color to OpenGL. Calls glClearColor (in RGBA mode) or glClearIndex (in color-index mode) with the color c. Applies to this widgets GL context.

See also
qglColor(), QGLContext::currentContext(), QColor
void QGLWidget::qglColor ( const QColor c) const

Convenience function for specifying a drawing color to OpenGL. Calls glColor4 (in RGBA mode) or glIndex (in color-index mode) with the color c. Applies to this widgets GL context.

Note
This function is not supported on OpenGL/ES 2.0 systems.
See also
qglClearColor(), QGLContext::currentContext(), QColor
QPixmap QGLWidget::renderPixmap ( int  w = 0,
int  h = 0,
bool  useContext = false 
)

Renders the current scene on a pixmap and returns the pixmap. You can use this method on both visible and invisible QGLWidget objects.

This method will create a pixmap and a temporary QGLContext to render on the pixmap. It will then call initializeGL(), resizeGL(), and paintGL() on this context. Finally, the widget's original GL context is restored.

The size of the pixmap will be w pixels wide and h pixels high unless one of these parameters is 0 (the default), in which case the pixmap will have the same size as the widget.

If useContext is true, this method will try to be more efficient by using the existing GL context to render the pixmap. The default is false. Only use true if you understand the risks. Note that under Windows a temporary context has to be created and usage of the useContext parameter is not supported.

Overlays are not rendered onto the pixmap.

If the GL rendering context and the desktop have different bit depths, the result will most likely look surprising.

The creation of display lists, modifications of the view frustum etc. should be done from within initializeGL(). If this is not done the temporary QGLContext will not be initialized properly and the rendered pixmap may be incomplete or corrupted.

void QGLWidget::renderText ( double  x,
double  y,
double  z,
const QString str,
const QFont font = QFont() 
)

This is an overloaded function.

x, y and z are specified in scene or object coordinates relative to the currently set projection and model matrices. This can be useful if you want to annotate models with text labels and have the labels move with the model as it is rotated etc.

Note
This function is not supported on OpenGL/ES systems.
If depth testing is enabled before this function is called, then the drawn text will be depth-tested against the models that have already been drawn in the scene. Use glDisable(GL_DEPTH_TEST) before calling this function to annotate the models without depth-testing the text.
void QGLWidget::renderText ( int  x,
int  y,
const QString str,
const QFont font = QFont() 
)

Renders the string str into the GL context of this widget.

x and y are specified in window coordinates, with the origin in the upper left-hand corner of the window. If font is not specified, the currently set application font will be used to render the string. To change the color of the rendered text you can use the glColor() call (or the qglColor() convenience function), just before the renderText() call.

Note
This function clears the stencil buffer. This function is not supported on OpenGL/ES systems. This function temporarily disables depth-testing when the text is drawn.
This function can only be used inside a QPainter::beginNativePainting() - QPainter::endNativePainting() block if the default OpenGL paint engine is QPaintEngine::OpenGL. To make QPaintEngine::OpenGL the default GL engine, call QGL::setPreferredPaintEngine(QPaintEngine::OpenGL) before the QApplication constructor.
void QGLWidget::resizeEvent ( QResizeEvent event)
overrideprotectedvirtual

Reimplemented from QWidget::resizeEvent().

Handles resize events that are passed in the event parameter. Calls the virtual function resizeGL().

Reimplemented from QWidget.

void QGLWidget::resizeGL ( int  width,
int  height 
)
protectedvirtual

This virtual function is called whenever the widget has been resized. The new size is passed in width and height. Reimplement it in a subclass.

There is no need to call makeCurrent() because this has already been done when this function is called.

void QGLWidget::resizeOverlayGL ( int  width,
int  height 
)
protectedvirtual

This virtual function is used in the same manner as paintGL() except that it operates on the widget's overlay context instead of the widget's main context. This means that resizeOverlayGL() is called whenever the widget has been resized. The new size is passed in width and height. Reimplement it in a subclass.

There is no need to call makeOverlayCurrent() because this has already been done when this function is called.

void QGLWidget::setAutoBufferSwap ( bool  on)
protected

If on is true automatic GL buffer swapping is switched on, otherwise it is switched off.

If on is true and the widget is using a double-buffered format, the background and foreground GL buffers will automatically be swapped after each paintGL() call.

The buffer auto-swapping is on by default.

See also
autoBufferSwap(), doubleBuffer(), swapBuffers()
void QGLWidget::setColormap ( const QGLColormap cmap)

Set the colormap for this widget to cmap. Usually it is only top-level widgets that can have colormaps installed.

See also
colormap()
void QGLWidget::setFormat ( const QGLFormat format)
deprecated
Deprecated:
Sets a new format for this widget.

If the underlying OpenGL/Window system can not satisfy all the features requested in format, the nearest subset of features will be used. After creation, the format() method will return the actual rendering context format obtained.

The widget will be assigned a new QGLContext, and the initializeGL() function will be executed for this new context before the first resizeGL() or paintGL().

This method will try to keep display list and texture object sharing in effect with other QGLWidget objects, but changing the format might make sharing impossible. Use isSharing() to see if sharing is still in effect.

See also
format(), isSharing(), isValid()
void QGLWidget::swapBuffers ( )

Swaps the screen contents with an off-screen buffer. This only works if the widget's format specifies double buffer mode.

Normally, there is no need to explicitly call this function because it is done automatically after each widget repaint, i.e. each time after paintGL() has been executed.

See also
doubleBuffer(), setAutoBufferSwap(), QGLFormat::setDoubleBuffer()
void QGLWidget::updateGL ( )
slot

Updates the widget by calling glDraw().

void QGLWidget::updateOverlayGL ( )
slot

Updates the widget's overlay (if any). Will cause the virtual function paintOverlayGL() to be executed.

The widget's rendering context will become the current context and initializeGL() will be called if it has not already been called.