Skip to content

Instantly share code, notes, and snippets.

@mivade
Last active April 11, 2016 03:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mivade/35cbd270f49e1ca7ba7d to your computer and use it in GitHub Desktop.
Save mivade/35cbd270f49e1ca7ba7d to your computer and use it in GitHub Desktop.
PyQt with Tornado
"""Demonstration of combining the Qt and Tornado event loops."""
from PyQt4 import QtGui, QtCore
from tornado.ioloop import IOLoop
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
URL = "https://www.random.org/integers/?num=1&min=100&max=999&col=1&base=10&format=plain&rnd=new"
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.label = QtGui.QLabel("Label!")
self.setCentralWidget(self.label)
def closeEvent(self, event):
IOLoop.instance().stop()
@gen.coroutine
def update_label(self):
label = yield AsyncHTTPClient().fetch(URL)
if label.error:
self.label.setText("Error!")
else:
self.label.setText(label.body.decode('utf-8'))
if __name__ == "__main__":
import sys
from threading import Thread
Thread(target=lambda: IOLoop.instance().start()).start()
app = QtGui.QApplication(sys.argv)
win = MainWindow()
win.show()
timer = QtCore.QTimer()
timer.setInterval(1000)
timer.timeout.connect(win.update_label)
timer.start()
sys.exit(app.exec_())
@maartenbreddels
Copy link

Nice fix, however it doesn't always work since the part after the yield statement is not executed in the main thread, see my solution here:
https://gist.github.com/maartenbreddels/9a31e4025ef9cc0ee68a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment