Search code examples
pythonpyqt5qwebengineviewqwebenginepage

QWebEngineView crashes when accessing specific websites


I have a very weird bug with QWebEngineView. Below is some code which creates a QWebEngineView.

import sys

from PyQt5.QtCore import QCoreApplication, QFileInfo, QUrl
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings, QWebEngineProfile, QWebEnginePage

class Widget(QWidget):
    def __init__(self):
        super().__init__()
        webview = QWebEngineView(self)
        webview.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
        profile = QWebEngineProfile("my_profile", webview)
        webpage = QWebEnginePage(profile, webview)
        webview.setUrl(QUrl("https://www.youtube.com"))
        #self.webview.setPage(self.webpage)
        webview.setGeometry(0, 0, 800, 480)
        webview.show()

        self.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Widget()
    app.exec_()

My issue is that when I run the code as it is (with the self.webview.setPage(self.webpage) line commented out) I am able to open PDF files, however opening YouTube crashes the program. However if I uncomment the line and run it, I can't open PDF files (although it doesn't crash the program it just doesn't open the PDF file), but I can then open YouTube with no issue.


Solution

  • You have to set the QWebEngineProfile and QWebEnginePage first and then enable the plugins:

    import sys
    
    from PyQt5.QtCore import QUrl
    from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget
    from PyQt5.QtWebEngineWidgets import (
        QWebEnginePage,
        QWebEngineProfile,
        QWebEngineSettings,
        QWebEngineView,
    )
    
    
    class Widget(QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
    
            profile = QWebEngineProfile("my_profile", self)
            webpage = QWebEnginePage(profile, self)
            webview = QWebEngineView(self)
            webview.setPage(webpage)
            webview.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
            webview.load(QUrl("https://www.youtube.com"))
    
            lay = QVBoxLayout(self)
            lay.addWidget(webview)
            self.resize(640, 480)
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        w = Widget()
        w.show()
        app.exec_()