Search code examples
pythonqtpyqtpyqt5qml

QtWebEngine::initialize() with PyQT


I have code bellow:

import sys

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine


app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

sys.exit(app.exec())

and qml file:

import QtQuick 2.15
import QtQuick.Window 2.15
import QtWebEngine 1.2

Window {
    visible: true
    title: "HelloApp"

    WebEngineView{
        anchors.fill: parent
        url: "http://google.com"
    }

}

When I am trying to run the app I see an error: WebEngineContext used before QtWebEngine::initialize() or OpenGL context creation failed.

Question: how can I call QtWebEngine::initialize() in PyQT?


Solution

  • The full error message gives you a hint about what you should do to solve it:

    Qt WebEngine seems to be initialized from a plugin. Please set Qt::AA_ShareOpenGLContexts using QCoreApplication::setAttribute and QSGRendererInterface::OpenGLRhi using QQuickWindow::setGraphicsApi before constructing QGuiApplication.
    WebEngineContext is used before QtWebEngineQuick::initialize() or OpenGL context creation failed.
    

    You need to add QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts, True) before initializing the QGuiApplication and don't forget the QtCore import. Qt 5 or 6 shouldn't matter in this case.

    import sys
    
    from PySide6 import QtCore
    from PySide6.QtGui import QGuiApplication
    from PySide6.QtQml import QQmlApplicationEngine
    
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts, True)
    
    app = QGuiApplication(sys.argv)
    
    engine = QQmlApplicationEngine()
    engine.quit.connect(app.quit)
    engine.load('main.qml')
    
    sys.exit(app.exec())