我正在寻找一个基于线程。线程,多处理或队列以上载具有超时的项目列表。线程允许GUI保持响应。如果连接挂起,则应触发超时并正常退出程序。在
下面的示例可以工作,但是GUI仍然被阻塞。如何改进这一点以允许上传列表、手动取消进程、上传过程超时以及非阻塞GUI?在
from PySide.QtGui import *
from PySide.QtCore import *
import sys
import time
import threading
class UploadWindow(QDialog):
def __init__(self, parent=None):
super(UploadWindow, self).__init__(parent)
self.uploadBtn = QPushButton('Upload')
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.uploadBtn)
self.uploadBtn.clicked.connect(self.do_upload)
self.progressDialog = QProgressDialog(self)
self.progressDialog.canceled.connect(self.cancelDownload)
self.progressDialog.hide()
self.setLayout(mainLayout)
self.show()
self.raise_()
def do_upload(self):
self.uploadBtn.setEnabled(False)
self.progressDialog.setMaximum(10)
self.progressDialog.show()
self.upload_thread = UploadThread(self)
self.upload_thread.start()
self.upload_thread_stopped = False
#List of items to upload
for i in range(10):
self.upload_thread = UploadThread(i)
self.upload_thread.start()
self.upload_thread.join(5)
self.progressDialog.setValue(i)
if self.upload_thread_stopped:
break
self.progressDialog.hide()
self.uploadBtn.setEnabled(True)
def cancelDownload(self):
self.upload_thread_stopped = True
class UploadThread(threading.Thread):
def __init__(self, i):
super(UploadThread, self).__init__()
self.i = i
self.setDaemon(True)
def run(self):
time.sleep(0.25) #simulate upload time
print self.i
if __name__ == '__main__':
app = QApplication(sys.argv)
w = UploadWindow()
sys.exit(app.exec_())
最后,我通过采用概述的here方法解决了这个问题,我发现这是一个优雅的解决方案。我创建的类如下所示:
在主线程中,创建上载线程,并在输入_q中加载要上载的项。创建了一个QTimer,通过检查结果中的内容来定期检查上传的进度。它还更新进度条。如果在超时时间内没有任何进展,则表明上载连接失败。在
使用的优点排队。排队对象用于线程之间的通信,即可以创建共享同一输入和结果队列的多个线程。在
GUI没有响应,因为您在
do_upload
中完成所有工作,从不返回主循环。在另外,您可以调用
Thread.join()
,在线程完成之前阻塞所有内容(请参见https://docs.python.org/2/library/threading.html#threading.Thread.join)您应该使用
PySide.QtCore.QThread
来利用信号和插槽。 这是一个nice example in C++。我用PyQthere在Python3.4中实现了它,但是您也应该能够在PySide中使用它。在您可能还需要查看
PySide.QtCore.QProcess
,以避免使用线程。在在这里,我把一些代码组合在一起,可以实现我认为你想要的。在
对于实际的项目,请确保更好地跟踪上载的内容&;/或使用比.terminate()更安全的方法来按需停止线程。在
相关问题 更多 >
编程相关推荐