Search code examples
qtnetwork-programmingwebkittimeoutqtwebkit

Qt QWebView network timeout values and signals


How can a QWebView be configured to lower network timeout values - so that in the event of the network failure the loadFinished(bool ok) signal can be reached sooner, obviously, with a false value and an appropriate error condition set?

Bonus points for handling different timeouts differently


Solution

  • Standard errors and successful page loading will trigger loadFinished the same way as before, but a custom timer will stop the webpage loading and trigger loadFinished with ok=False

    class Browser(object):
    
        def __init__(self):
            self.web_view = QWebView()
            self.web_view.loadFinished.connect(self._load_finished)
    
            self._error = None
    
        def perform(self, url, timeout_value=30):
            request = QNetworkRequest()
            request.setUrl(QUrl(url))
    
            self.timeout_timer = QTimer()
            self.timeout_timer.timeout.connect(self._request_timed_out)
    
            self.timeout_timer.start(timeout_value * 1000)
            self.web_view.load(request)
    
        def _request_timed_out(self):
            self._error = 'Custom request timeout value exceeded.'
            self.timeout_timer.stop()
            self.web_view.stop()
            self.loadFinished.emit(False)
    
        def _load_finished(self, ok):
            pass
            # ok is now False, and self._error contains a custom error message