嵌套的DirectConnection信号导致段错误

时间:2014-12-29 14:38:08

标签: c++ multithreading qt pyside

这是我unanswered question here的后续行动。代码完全如下所示,使用段错误(将其复制/粘贴到系统中并运行)。当我从一个或两个信号构造函数调用中删除type=QtCore.Qt.DirectConnection(从而改为使用QtCore.Qt.AutoConnection)时,一切都按照应有的方式运行:出现一个小部件,显示五个进度条填满然后在无尽的情况下清空循环。

from PySide import QtCore, QtGui
import time

class Worker(QtCore.QThread):
    sig_worker_update_progress = QtCore.Signal(int, int)

    def __init__(self, thread_id, *args, **kwargs):
        super(Worker, self).__init__(*args, **kwargs)
        self.thread_id = thread_id
        self.stop_requested = False

    def slot_interrupt(self):
        self.stop_requested = True

    def run(self):
        progress = 0
        while(True):
            self.sig_worker_update_progress.emit(self.thread_id, progress % 100)
            progress += 1
            if self.stop_requested:
                break
            else:
                time.sleep(0.1)


class Controller(QtCore.QObject):
    sig_controller_update_progress = QtCore.Signal(int, int)

    def __init__(self, num_workers, *args, **kwargs):
        super(Controller, self).__init__(*args, **kwargs)

        self.workers = []
        for i in range(num_workers):
            self.workers.append(Worker(i))
            self.workers[i].sig_worker_update_progress.connect(
                self.slot_worker_update_progress,
                type=QtCore.Qt.DirectConnection)
        for worker in self.workers:
            worker.start()

    def slot_worker_update_progress(self, thread_id, progress):
        # Do
        # Stuff
        self.sig_controller_update_progress.emit(thread_id, progress)


class Monitor(QtGui.QWidget):
    def __init__(self, num_workers, *args, **kwargs):
        super(Monitor, self).__init__(*args, **kwargs)
        main_layout = QtGui.QVBoxLayout()
        self.setLayout(main_layout)
        self.progress_bars = []

        for _ in range(num_workers):
            progress_bar = QtGui.QProgressBar()
            main_layout.addWidget(progress_bar)
            self.progress_bars.append(progress_bar)

        self.controller  = Controller(num_workers)
        self.controller.sig_controller_update_progress.connect(
            self.slot_controller_update_progress,
            type=QtCore.Qt.DirectConnection)

    def slot_controller_update_progress(self, thread_id, progress):
        self.progress_bars[thread_id].setValue(progress)


if __name__ == "__main__":
    app = QtGui.QApplication([])
    monitor = Monitor(5)
    monitor.show()
    app.exec_()

为什么使用两个嵌套的DirectConnection信号会导致段错误?如果Qt不希望你这样做,为什么不给出更多信息错误?

我正在使用包含Qt 4.8框架的PySide v1.2.2。

1 个答案:

答案 0 :(得分:1)

我找到了令人满意的解释here。显然,发出DirectConnection类型的信号相当于直接函数调用。因此,当两个信号均为Worker时,GUI在DirectConnect线程上进行了更新。正如我在other question中所提到的,不允许线程更改GUI。问题不在于嵌套DirectConnection本身。