Search code examples
pyqtpyqt5

RuntimeError: wrapped C/C++ object of type QWebEngineDownloadItem has been deleted in PyQt


I wrote a web browser

What I want to do is when I click on the download links, a new window will open to manage the downloads and manage the tasks of starting downloads and stopping downloads in a new window(download manager window)

When I click on the download links,

a new window (download manager window) opens But when I click on the start button in the download manager window, I get this error

RuntimeError: wrapped C/C++ object of type QWebEngineDownloadItem has been deleted

#my Code:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
import os
import sys
from functools import partial

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.browser = QWebEngineView()
        self.browser.page().profile().downloadRequested.connect(self.openDownloadManagerWindow)
        self.browser.setUrl(QUrl("http://google.com"))
        self.setCentralWidget(self.browser)
        navtb = QToolBar("Navigation")
        self.addToolBar(navtb)
        self.urlbar = QLineEdit()
        self.urlbar.returnPressed.connect(self.navigate_to_url)
        navtb.addWidget(self.urlbar)
        self.show()
 
    
    #download manager window
    def openDownloadManagerWindow(self , download):
        self.downloadWindow = QDialog()
        self.downloadWindow.resize(400,200)
        self.start_button = QPushButton("Start" , self.downloadWindow)
        self.stop_button = QPushButton("Stop" , self.downloadWindow)
        self.stop_button.move(320,0)
        self.downloadWindow.show()

        self.start_button.clicked.connect(partial(self.start , download))

    def start(self , download):
        download.accept()

    def navigate_to_url(self):
        q = QUrl(self.urlbar.text())
        if q.scheme() == "":
            q.setScheme("http")
        self.browser.setUrl(q)

 

app = QApplication(sys.argv)
window = MainWindow()
app.exec_()

Solution

  • According to the documentation :

    If accept() is not called by any signal handler, then the [QWebEngineDownloadItem] will be deleted immediately after signal emission. This means that the application must not keep references to rejected download items.

    So you need to accept the download in your openDownloadManagerWindow, since it will otherwise be deleted at the end of the function, and cause your application to break.