Skip to content

Instantly share code, notes, and snippets.

Created April 28, 2014 15:34
Show Gist options
  • Save anonymous/b24d33c81bd619700b3b to your computer and use it in GitHub Desktop.
Save anonymous/b24d33c81bd619700b3b to your computer and use it in GitHub Desktop.
PyQt 4 Qt network request from JavaScript function in WebView
from PyQt4 import QtCore, QtGui, QtNetwork, QtWebKit
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
QtNetwork.QNetworkProxyFactory.setUseSystemConfiguration(True)
self.view = QtWebKit.QWebView(self)
self.setCentralWidget(self.view)
self.view.setPage(QtWebKit.QWebPage(self.view))
self.view.page().mainFrame().javaScriptWindowObjectCleared.connect(self.refreshJS)
self.view.setHtml(
'''<html>
<body>
LOADING...
<script>
<!--
APP.request();
//-->
</script>
</body>
</html>'''
)
@QtCore.pyqtSlot()
def request(self):
request = QtNetwork.QNetworkRequest(QtCore.QUrl('http://localhost/test.php'))
manager = QtNetwork.QNetworkAccessManager()
manager.finished.connect(self.managerFinished)
reply = manager.post(request, b'a=A')
reply.finished.connect(self.finished)
##########################################################
### FIXME: Request never completes if this is missing ###
##########################################################
while not reply.isFinished():
QtGui.QApplication.processEvents()
##########################################################
print('request FINISHED? '+str(reply.isFinished())+', ERROR '+str(reply.error()))
def finished(self):
print('finished')
def managerFinished(self):
print('managerFinished')
def refreshJS(self):
print('refreshJS')
self.view.page().mainFrame().addToJavaScriptWindowObject('APP', self)
if __name__ == '__main__':
import os, sys
app = QtGui.QApplication(sys.argv)
MainWindow().show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment