Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
pyqt web view
import sys
from PyQt4.QtCore import QTimer, QVariant, SIGNAL
from PyQt4.QtGui import *
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
from PyQt4.QtWebKit import QWebView
html = """<html>
<head>
<title>Test page for the download:// scheme</title>
</head>
<body>
<h1>Downloads</h1>
<a href="download://myfile">Download a file</a>
<hr />
<a href="http://www.google.com">A normal link</a>
</body>
</html>
"""
# class that returns data to browser
class DownloadReply:
def __init__(self, parent, url, operation):
QNetworkReply.__init__(self, parent)
self.content = "<html><head><title>Test</title></head><body>This is a test.</body></html>"
self.content = "<html><head><title>Test</title></head><body>This is a test.</body></html>"
self.offset = 0
self.setHeader(QNetworkRequest.ContentTypeHeader, QVariant("text/html; charset=ASCII"))
self.setHeader(QNetworkRequest.ContentLengthHeader, QVariant(len(self.content)))
QTimer.singleShot(0, self, SIGNAL("readyRead()"))
QTimer.singleShot(0, self, SIGNAL("finished()"))
self.open(self.ReadOnly | self.Unbuffered)
self.setUrl(url)
def abort(self):
pass
def bytesAvailable(self):
# NOTE:
# This works for Win:
# return len(self.content) - self.offset
# but it does not work under OS X.
# Solution which works for OS X and Win:
# return len(self.content) - self.offset + QNetworkReply.bytesAvailable(self)
return len(self.content) - self.offset
def isSequential(self):
return True
def readData(self, maxSize):
if self.offset < len(self.content):
end = min(self.offset + maxSize, len(self.content))
data = self.content[self.offset:end]
self.offset = end
return data
class NetworkAccessManager(QNetworkAccessManager):
def __init__(self, old_manager):
QNetworkAccessManager.__init__(self)
self.old_manager = old_manager
self.setCache(old_manager.cache())
self.setCookieJar(old_manager.cookieJar())
self.setProxy(old_manager.proxy())
self.setProxyFactory(old_manager.proxyFactory())
def createRequest(self, operation, request, data):
if request.url().scheme() != "download":
return QNetworkAccessManager.createRequest(self, operation, request, data)
if operation == self.GetOperation:
# Handle download:// URLs separately by creating custom
# QNetworkReply objects.
reply = DownloadReply(self, request.url(), self.GetOperation)
return reply
else:
return QNetworkAccessManager.createRequest(self, operation, request, data)
if __name__ == "__main__":
app = QApplication(sys.argv)
view = QWebView()
old_manager = view.page().networkAccessManager()
new_manager = NetworkAccessManager(old_manager)
view.page().setNetworkAccessManager(new_manager)
view.setHtml(html)
view.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment