Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Solved Make QGuiApplication to use an external QOpenGLContext?

    Game Development
    1
    2
    1135
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • T
      Timothy last edited by

      I'd like to be able to set up a QOpenGLContext and then tell my QGuiApplication to use said context. Is this possible?

      T 1 Reply Last reply Reply Quote 0
      • T
        Timothy @Timothy last edited by

        I ended up solving this myself. Here's sample code which shows how to set up context sharing between Qt's context and some external context:

        // These functions would wrap some other library that can create windows and contexts, like glfw for example
        void create_external_context();
        HGLRC get_native_context_handle();
        HWND get_native_window_handle();
        
        int main(int argc, char* argv[]) {
            // create an opengl context
            create_external_context();
        
            // set opengl version and options
            QSurfaceFormat format;
            format.setVersion(4, 5);
            format.setProfile(QSurfaceFormat::CoreProfile);
            format.setDepthBufferSize(24);
            format.setStencilBufferSize(8);
            QSurfaceFormat::setDefaultFormat(format);
        
            // this must be set to enable context sharing
            QGuiApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
        
            QGuiApplication app(argc, argv);
        
            // Create a Qt context which wraps the external native context.
            QOpenGLContext nativeContext;
            // This will be platform specific. The following is windows only
            QWGLNativeContext wglcontext(get_native_context_handle(), get_native_window_handle());
            QVariant qv;
            qv.setValue<QWGLNativeContext>(wglcontext);
            nativeContext.setNativeHandle(qv);
            nativeContext.create();
        
            // Tell Qt to use the external context as the global sharing context
            QOpenGLContext * qtGlobalContex = QOpenGLContext::globalShareContext();
            qtGlobalContex->setShareContext(&nativeContext);
            // recreate after setting native shared context
            qtGlobalContex->create();
        
            // at this point it is safe to start a separate thread and bind the external context to it
            // start the app only after the contexts have been set up
            engine.load(QUrl("qrc:/main.qml"));
            return app.exec();
        }
        
        1 Reply Last reply Reply Quote 1
        • First post
          Last post