如何暂停在Qpushbutton Press上执行QThread



我正在使用pyqt4为灯板(Wiki)编写一个简单的GUI。GUI具有一个"求解"按钮,该按钮使用迭代加深深度的第一次搜索。这很耗时,我产生了一个新的QThread来解决难题,并在GUI响应时完成董事会时进行更新。我可以做到这一点。

但是,我也有一个"停止"按钮,如果搜索线程当前正在运行,则应停止搜索线程,并且我无法使用exit()停止QThread。这是三个函数的代码。

class LightsOut(QWidget):
    def __init__(self, parent=None):
        # Whole other initialization stuff
        self.pbStart.clicked.connect(self.puzzleSolver) # The 'Start' Button
        self.pbStop.clicked.connect(self.searchStop) # The 'Stop' Button
    def searchStop(self):
        if self.searchThread.isRunning():
            self.searchThread.exit() # This isn't working
            self.tbLogWindow.append('Stopped the search !') # This is being printed
        else:
            self.tbLogWindow.append('Search is not running')
    def searchFinish(self):
        self.loBoard.setBoard() # Redraw the lights out board with solution
    def puzzleSolver(self):
        maxDepth = self.sbMaxDepth.value() # Get the depth from Spin Box
        self.searchThread = SearchThread(self.loBoard, self.tbLogWindow, maxDepth)
        self.searchThread.finished.connect(self.searchFinish)
        self.tbLogWindow.append('Search started')
        self.searchThread.start()

当我单击"停止"按钮时,在日志窗口(qtextbrowser)中,我可以看到"停止搜索"消息,但是我的CPU仍以100%的速度运行,搜索完成时,正在显示解决方案(称为搜索finish)。显然,我缺少一些非常简单的东西,而且我没有像文档中皱眉那样使用terminate()。

使用terminate()代替quit并调用wait()wait()将阻止直到QThread完成。

您可以做的另一件事是在线程之外设置戒烟条件,您将在线程内检查该条件(可能是最好的解决方案)。另外,您可以将插槽连接到finished信号。

最新更新