在Python中进行线程化而不是将UI与工作线程分开

时间:2015-12-07 19:34:51

标签: python multithreading pyqt pyqt4

我在这里失踪了。虽然在两个单独的线程中运行,但UI仍未按预期更新。它仍然落后于dd工作线程。

from ui import Ui_main_window
from PyQt4 import QtGui, QtCore

import sys
import subprocess
import commands
import threading

from time import sleep

out_int = 0

def _dd_thread_run(_if, _of, _bs, _size):
    _dd_subprocess_command_format = "dd if=%s bs=%s | pv -n --size %s | dd of=%s" % (_if, _bs, _size, _of)
    _dd_subprocess_command = [_dd_subprocess_command_format]
    _dd_progress = subprocess.Popen(_dd_subprocess_command, shell=True, stderr=subprocess.PIPE)
    while _dd_progress.poll() is None:
        out = _dd_progress.stderr.readline().replace("\n", "")
        global out_int 
        out_int = int (out)

def _ui_progress_set():
    class MainWindow(QtGui.QMainWindow, Ui_main_window):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.setupUi(self)

    app = QtGui.QApplication(sys.argv)
    ui = MainWindow()
    ui.show()
    while True:
        for i in range(100):
            ui.progressBar.setValue(out_int)
            sleep(.1)


t1 = threading.Thread(target=_dd_thread_run, args = ["/dev/urandom", "/dev/null", "100K", "100M"])
t1.start()
t2 = threading.Thread(target=_ui_progress_set, args = [])
t2.start()

我怀疑是Python或PyQt错误?无论UI类在何处定义,它都保持不变。

1 个答案:

答案 0 :(得分:0)

你没有在任何地方运行主事件循环 - 如果没有(see doc),你将无法显示。试试

app = QtGui.QApplication(sys.argv)
ui = MainWindow()
ui.show()
app.exec_()

没有while循环。 如果你的while循环应该创建一个不确定的进度条 - 可以通过将QProgressBar最小值和最大值设置为零来轻松实现。