I'm writing an PySide application that communicates with hardware over a serial connection.
I have a button to start the device command and a label to show the result to the user. Now some devices take a long time (multiple seconds) to answer a request, which freezes the GUI. I am searching for a simple mechanism to run the call in a background thread or similar.
I created a short example of what I am trying to accomplish:
import sys
import time
from PySide import QtCore, QtGui
class Device(QtCore.QObject):
def request(self, cmd):
time.sleep(3)
return 'Result for {}'.format(cmd)
class Dialog(QtGui.QDialog):
def __init__(self, device, parent=None):
super().__init__(parent)
self.device = device
self.layout = QtGui.QHBoxLayout()
self.label = QtGui.QLabel('--')
self.button = QtGui.QPushButton('Go')
self.layout.addWidget(self.label)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
self.button.clicked.connect(self.go)
def go(self):
self.button.setEnabled(False)
# the next line should be called in the
# background and not freeze the gui
result = self.device.request('command')
self.label.setText(result)
self.button.setEnabled(True)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dev = Device()
win = Dialog(device=dev)
win.show()
win.raise_()
app.exec_()
What I wish to have is some kind of function like:
result = nonblocking(self.device.request, 'command')
Exceptions should be raised as if I called the function directly.
Any ideas or recommendations?