QWebEngineView:显示加载进度

时间:2018-06-28 07:21:20

标签: python pyqt pyqt5 qwebengineview

我正在使用带有PyQt5和Python 3.6的QWebEngineView小部件。 页面加载时,我想显示进度。出于演示目的,我仅使用打印语句来完成此操作(以后,我想让进度条小部件出现,显示进度并在完成后消失)。

我已连接到loadStarted,loadProgress,loadFinished事件。

代码如下所示( self.browser 是QWebEngineView小部件):

def loadStartedHandler(self):
    print(time.time(), ": load started")

def loadProgressHandler(self, prog):
    print(time.time(), ":load progress", prog)

def loadFinishedHandler(self):
    print(time.time(), ": load finished")

# ....

self.browser.loadStarted.connect(lambda: self.loadStartedHandler())
self.browser.loadProgress.connect(lambda: self.loadProgressHandler(42))
self.browser.loadFinished.connect(lambda: self.loadFinishedHandler())

当然,现在我希望获取loadProgress事件的实际进度值,而不是数字42。我怎么得到这个?

对不起,如果这个问题很愚蠢。我是一个新手,只是无法从C ++文档将其转换为Python。 (不幸的是,我找不到Qt的像样的Python文档。)

1 个答案:

答案 0 :(得分:2)

不必传递Lambda,您可以使用new connection syntax直接将其连接:

def loadStartedHandler(self):
    print(time.time(), ": load started")

def loadProgressHandler(self, prog):
    print(time.time(), ":load progress", prog)

def loadFinishedHandler(self):
    print(time.time(), ": load finished")

   ....

    self.browser.loadStarted.connect(self.loadStartedHandler)
    self.browser.loadProgress.connect(self.loadProgressHandler)
    self.browser.loadFinished.connect(self.loadFinishedHandler)

示例:

import sys
import time

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self):
        super(Widget, self).__init__()
        lay = QtWidgets.QVBoxLayout(self)
        self.browser = QtWebEngineWidgets.QWebEngineView()
        lay.addWidget(self.browser)
        self.browser.setUrl(QtCore.QUrl("https://www.google.com"))
        self.browser.loadStarted.connect(self.loadStartedHandler)
        self.browser.loadProgress.connect(self.loadProgressHandler)
        self.browser.loadFinished.connect(self.loadFinishedHandler)

    @QtCore.pyqtSlot()
    def loadStartedHandler(self):
        print(time.time(), ": load started")

    @QtCore.pyqtSlot(int)
    def loadProgressHandler(self, prog):
        print(time.time(), ":load progress", prog)

    @QtCore.pyqtSlot()
    def loadFinishedHandler(self):
        print(time.time(), ": load finished")

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    view = Widget()
    view.show()
    sys.exit(app.exec_())