Search code examples
pythonpython-3.xpyside2web-inspectorqwebengineview

What is the alternative to QWebInspector in Qt WebEngine?


The example of the code snippet is here:

from PySide2 import QtCore, QtGui, QtWidgets, QtWebChannel
from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings

class AppWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.view = WebView(self)
        self.setCentralWidget(self.view)
        self.view.settings().setAttribute(QWebEngineSettings.JavascriptEnabled, True)
        self.view.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True);
        self.page = self.view.page()
        self.page.setDevToolsPage(self.page)

        #self.inspector = QWebInspector(self) # Crash is here!!!
        #self.inspector.setPage(self.page)
        #self.inspector.hide()

The three lines above were working perfectly in previous versions.

What is the alternative to QWebInspector in PySide2?


Solution

  • There is no equivalent QWebInspector class for QWebEngine, because the dev tools are provided by the underlying Chrome browser. An environment variable needs to be set to enable the tools, and you can then access them via a separate Chrome-based browser - see Qt WebEngine Developer Tools in the Qt5 docs for the full details.

    Below is a simple demo based on your example code:

    enter image description here

    import sys, os
    
    DEBUG_PORT = '5588'
    DEBUG_URL = 'http://127.0.0.1:%s' % DEBUG_PORT
    os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = DEBUG_PORT
    
    from PySide2 import QtCore, QtGui, QtWidgets, QtWebChannel
    from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings
    
    class AppWindow(QtWidgets.QMainWindow):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.view = QWebEngineView(self)
            self.setCentralWidget(self.view)
            self.view.settings().setAttribute(QWebEngineSettings.JavascriptEnabled, True)
            self.view.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
    
            self.view.loadFinished.connect(self.handleLoaded)
            self.view.load(QtCore.QUrl('https://google.com/'))
    
            self.inspector = QWebEngineView()
            self.inspector.setWindowTitle('Web Inspector')
            self.inspector.load(QtCore.QUrl(DEBUG_URL))
    
        def handleLoaded(self, ok):
            if ok:
                self.view.page().setDevToolsPage(self.inspector.page())
                self.inspector.show()
    
    app = QtWidgets.QApplication(sys.argv)
    win = AppWindow()
    win.setGeometry(600, 100, 600, 480)
    win.show()
    app.exec_()