【发布时间】:2015-02-17 06:21:27
【问题描述】:
我正在编写一个通过串行连接与硬件通信的 PySide 应用程序。
我有一个按钮来启动设备命令和一个标签来向用户显示结果。 现在一些设备需要很长时间(几秒钟)来响应请求,这会冻结 GUI。我正在寻找一种简单的机制来在后台线程或类似线程中运行调用。
我创建了一个我想要完成的简短示例:
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_()
我想要的是某种功能,例如:
result = nonblocking(self.device.request, 'command')
应该像我直接调用函数一样引发异常。
有什么想法或建议吗?
【问题讨论】:
标签: python multithreading pyqt pyside