'QWebEnginePage' object has no attribute 'mainFrame' and attribute 'print_'


Using QWebEnginePage I got the error message.

 'QWebEnginePage' object has no attribute 'mainFrame'  and attribute 'print_'

I tested using source code in https://github.com/mfitzp/15-minute-apps/tree/master/browser page. How can I fix this error?


This took a little effort to work out :smiley: — the problem comes from changes in the API for PyQt5.6 and up.


For printing web pages, the print method is now on the page object itself. This method print() accepts a printer object and callback to call once printing is complete. There is a bit of trickiness here in that if you try and use the QPrinter from the print dialog it will crash (probably due to losing a reference to the object).

The solution is to create a single QPrinter instance at startup and pass that into the dialog.

def print_page(self):
    dlg = QPrintDialog(self.printer)
    if dlg.exec_():
        self.browser.page().print(self.printer, self.print_completed)

def print_completed(self, success):
    pass   # Do something in here, maybe update the status bar?

The callback is required, but your not required to do anything in it. It receives a bool value for success/failure of the print.

Note that you need to create an instance of QPrinter in your window setup, e.g.

self.printer = QPrinter()


For mainFrame this has simply been deprecated. However, for the saving of files we now also need to use callbacks in the toHtml call. A working example is —

def save_file(self):
    filename, _ = QFileDialog.getSaveFileName(self, "Save Page As", "",
                                              "Hypertext Markup Language (*.htm *html);;"
                                              "All files (*.*)")

    if filename:
        def write_html_to_file(html):
            with open(filename, 'w') as f:

The simple solution is to create a little callback function to accept the generated html and complete the write to disk. For a real application you’d probably want some error handling in here too.