无法终止PyQT QThread

时间:2015-06-23 07:17:40

标签: python multithreading qt pyqt qthread

此问题与我的previous one

有关

如果我在position:relative项目之间切换太快,就会出现问题。 Alpha to Gamma run()方法无法在没有错误的情况下完成循环,因为当我在GenericThread

项之间切换时,提供给它的信息会发生变化

我已经添加了List1,但在这种情况下,这不是最好的解决方法,我必须终止该线程,如果它正在运行然后再次启动,但是当我和#39; m终止它,GUI冻结永远(但它不像它在项目之间切换时一直冻结,有时候self.terminate()有时不工作并且冻结我无法找出原因)...

exeptions

现在,为什么GUI freez以及如何正确地指定class GenericThread(QtCore.QThread): def __init__(self, parent=None): QtCore.QThread.__init__(self, parent) def stop(self): self.terminate() def __del__(self): self.quit() self.wait() def run(self): #Some very long stuff self.emit( QtCore.SIGNAL('itemSelectionChanged()')) return class MainUI(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self) self.ui = Ui_Win() self.ui.setupUi(self) self.genericThread = GenericThread(self, listIndex=2) self.connect(self.genericThread, QtCore.SIGNAL("fillListWithItems(QString, int)"), self.fillListWithItems ) self.ui.List1.list1SelectedItem.connect(self.fill_List2) ... def fill_List2(self): if self.genericThread.isRunning(): self.genericThread.stop() self.ui.List2.clear() list1SelectedItem = str(self.ui.List1.currentItem().text()) self.genericThread.start()

1 个答案:

答案 0 :(得分:2)

基于你的评论,@ jehumoro和@Pavel我已经修复了我的问题,现在它按照我的意愿运行,如果有效的话,eventhought self.terminate()会好得多。

class GenericThread(QtCore.QThread):
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.stopFlag = False

    def stop(self):
        self.stopFlag = True

    def __del__(self):
        self.quit()
        self.wait()

    def run(self):
        #Some very long stuff
            if self.stopFlag:
                self.stopFlag = False #Resetting the flag (in my case I have to do this!)
                break #Breaks main loop to finish 'run()'
            else:
                self.emit( QtCore.SIGNAL('itemSelectionChanged()'))

class MainUI(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_Win()
        self.ui.setupUi(self)

        self.genericThread = GenericThread(self, listIndex=2)
        self.connect(self.genericThread, QtCore.SIGNAL("fillListWithItems(QString, int)"), self.fillListWithItems )
        self.ui.List1.list1SelectedItem.connect(self.fill_List2)
        ...

    def fill_List2(self):
        if self.genericThread.isRunning():
            self.genericThread.stop()
        self.ui.List2.clear()
        list1SelectedItem = str(self.ui.List1.currentItem().text())
        self.genericThread.start()