简体   繁体   中英

How to wait for scripts to finish after QWebEngineView().loadFinished?

I'm trying to render an HTML file as a PDF with PyQt5. Unfortunately, my HTML page loads slow, but I couldn't find a way to wait for it to load. My question is this; How can I make PyQt5 wait for a couple of seconds, after resuming the execution? Or is there a better way to wait for JS scripts to execute?

app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(loader.close)
loader.load(QtCore.QUrl(url))

def emit_pdf(finished):
    loader.page().printToPdf("test.pdf")
    
loader.loadFinished.connect(emit_pdf)
    
app.exec()

I tried using QTimer but couldn't make it work. Here is how it looked like.

app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(loader.close)
loader.load(QtCore.QUrl(url))

timer = QtCore.QTimer()
timer.setInterval(2000)

def run_emit():
    loader.loadFinished.connect(emit_pdf)

timer.timeout.connect(run_emit)
timer.start()

def emit_pdf(finished):
    timer.stop()
    loader.page().printToPdf("test.pdf")
app.exec()

There is no Explicit wait for the final product. Instead of using QTimer.start() or QTimer.stop() , QTimer.singleShot() with a lambda function will work.

def emit_pdf(finished):
    QTimer.singleShot(2000, lambda: loader.page().printToPdf("test.pdf"))

app.exec()

I added this in case the solution comment is lost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM