c++multithreadingqtopenglqt5.5

QOpenGLWidget with shared OpenGL context?


I have an existing OpenGL context that I would like to share with a new QOpenGLWidget.

I know I can do this:

  1. Create QOpenGLWidget
  2. Wait until initializeGL is called and save the context
  3. Create new QOpenGLContext, and make it shared with the saved context

However, I would like to do it in the other order:

  1. Create QOpenGLContext
  2. Create QOpenGLWidget, providing the existing context and making them shared

Is this possible?


Solution

  • Edit, I don't know much about QOpenGLFramebufferObject yet so ignore my previous answer content.

    In the QOpenGLWidget it always sets its context to share with its closest top level window (or itself if it is a window). You are correct in your understanding that there is no way to change the QOpenGLWidget member context without subclassing it to totally change how it works. In the QOpenGLWidgetPrivate::initialize() function the context is initialized from the defaultFormat and from the top level shareContext. If you want to work with the context before you create the QOpenGLWidget then it must be through the global shared context. Qt::AA_ShareOpenGLContexts needs to be set before your QGuiApplication object is created.

    You need to wait until QGuiApplication has initialized the global context before you try to access it. As the global_share_context is a static member of the QOpenGLContext class then you can just create any QOpenGLContext and access it via context.globalShareContext(). Then just delete your initial QOpenGLContext. Any QOpenGLWidget you create will share with that context automatically. If you can find a way of getting a pointer to the global shared context before you create() your special context then you can just share with the global context and you are good to go as the sharing goes both ways. The sharing is through the whole group of shared contexts that are shared with each other so any sharing with one context shares with the whole group.

    Also, I don't know if this changes anything but The QOpenGLContext says it can share framebuffer objects too.