Created
October 15, 2012 22:19
-
-
Save nitely/3895989 to your computer and use it in GitHub Desktop.
Pyqt / Pyside: thread-safe global queue + main loop integration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Queue | |
#Global queue, import this from anywhere, you will get the same object. | |
#real life example: https://github.com/nitely/ochDownloader/blob/master/core/idle_queue.py | |
idle_loop = Queue.Queue() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PySide.QtGui import * | |
from PySide.QtCore import * | |
import idle_queue | |
class ThreadDispacher(QThread): | |
def __init__(self, parent): | |
QThread.__init__(self) | |
self.parent = parent | |
def run(self): | |
while True: | |
callback = idle_loop.get() | |
if callback is None: | |
break | |
QApplication.postEvent(self.parent, _Event(callback)) | |
def stop(self): | |
idle_loop.put(None) | |
self.wait() | |
class _Event(QEvent): | |
EVENT_TYPE = QEvent.Type(QEvent.registerEventType()) | |
def __init__(self, callback): | |
#thread-safe | |
QEvent.__init__(self, _Event.EVENT_TYPE) | |
self.callback = callback |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PySide.QtGui import * | |
from PySide.QtCore import * | |
from idle_queue_dispacher import ThreadDispacher | |
class Gui(QMainWindow): | |
def __init__(self): | |
QMainWindow.__init__(self) | |
#.... | |
self.dispacher = ThreadDispacher(self) | |
self.dispacher.start() | |
self.show() | |
def customEvent(self, event): | |
#process idle_queue_dispacher events | |
event.callback() | |
if __name__ == "__main__": | |
app = QApplication(['']) #QApplication(sys.argv) | |
gui = Gui() | |
app.exec_() | |
gui.dispacher.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment