暂停&恢复QThread

时间:2015-05-16 23:04:18

标签: python pyqt pyqt4 qthread

我正在尝试暂停QThread并恢复它。

所以,我在QThread中有一个RFID阅读循环,我想在读者获得RFID代码时暂停无限循环。之后,有一个数据库检查。在检查结束时,我想恢复RFID阅读循环以获取其他代码。

MVCE:

def main():
    global Thread
    app = QtGui.QApplication(sys.argv)
    main = Main()
    Thread = RFID_Thread()
    Thread.rfid_event.connect(Main().on_event)
    Thread.start()
    sys.exit(app.exec_())

class Main(object):
    def __init__(self):
        self.accueil = MainWindow(self)
        self.access = AccessWindow()
        self.accueil.show()

    def on_event(self, data):
        # I WANT TO PAUSE THE QTHREAD HERE

        ###################################
        #   CHECKING DB & SHOWING UI      #
        ###################################

        # AND RESUME IT HERE
class RFID_Thread(QtCore.QThread):
    rfid_event = pyqtSignal(str, name='rfid_event')
    def run(self):
        while 1:
            ser = serial.Serial(port=Serial_Port, baudrate=Serial_Baudrate)
            a = ser.read(19).encode('hex')
            ser.close()
            if len(a) <> 0:
                Code = a[14:]
                self.rfid_event.emit(Code)
                time.sleep(2)

if __name__=='__main__':
    main()

代码无法再现,因为您需要RFID阅读器,但我们可以通过这两行来模拟他,而不是打开串口并从中读取数据:

a = "**************e20030654408021520403f4b"
time.sleep(4)

我尝试使用状态变量,但它不起作用。

2 个答案:

答案 0 :(得分:2)

最后,我自己解决了这个问题

MVCE:

 split("(?<!^|[a-zA-Z'])|(?![a-zA-Z'])")

最后,状态变量是解决方案!!

答案 1 :(得分:0)

您可以使用 time 模块设置睡眠时间 例如单击暂停按钮时。

代码

import sys,time
from PyQt5 import QtWidgets,QtCore

class Thread(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)
        self.pause = False
    def run(self):
        for i in range(100):
            if self.pause:
                print("Paused")
                while self.pause:time.sleep(1)
            print("Number: "+str(i))
            time.sleep(1)
class App(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'QThread Pause test'
        self.left = 10
        self.top = 10
        self.width = 320
        self.height = 200
        self.initUI()
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.button = QtWidgets.QPushButton('Pause', self)
        self.button.move(175,75) 
        self.button.clicked.connect(self.thread_pause_resume)
        self.thread = Thread()
        self.show()
        self.thread.start()
    @QtCore.pyqtSlot()
    def thread_pause_resume(self):
        if self.button.text() == "Pause":
            self.thread.pause = True
            self.button.setText("Resume")
        else:
            self.thread.pause = False
            self.button.setText("Pause")

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())