-1
以下のコードは、ラベルとボタンを持つ単一のダイアログを作成します。 ボタンを押すとonClick
関数が呼び出され、がタスクとして機能し、queue
がthread
をトリガーとしてジョブを実行します。スレッドの完了後にウィジェットを更新する方法
スレッドが完了したら、dialog.onThreadCompleted
メソッドに呼び出して、計算結果を引数として渡します。この方法ではthread
の計算結果をself.label
に更新します。それを達成する方法?
import threading
import Queue as Queue
import functools
global queue
queue = Queue.Queue()
class Thread(QThread):
def __init__(self, parent=None):
QThread.__init__(self, parent)
def run(self):
global queue
while True:
partial = queue.get()
output = partial()
queue.task_done()
threads = []
thread = Thread()
threads.append(thread)
thread.start()
def calculate(number):
for i in range(number):
i += i
print 'calculate completed. result: %s' % i
return i
class Dialog(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.setLayout(QVBoxLayout())
self.label = QLabel(self)
self.label.setText('This label should display result')
self.layout().addWidget(self.label)
button = QPushButton('Start process')
button.clicked.connect(self.onClick)
self.layout().addWidget(button)
def onThreadCompleted(self, result):
self.label.setText(str(result))
def onClick(self):
self.label.setText('Calculation is starting...')
partial = functools.partial(calculate, number=100000000)
queue.put(partial)
if __name__ == '__main__':
app = QApplication([])
dialog = Dialog()
dialog.show()
qApp.exec_()