PyQT GUI在QThread中使用无限循环冻结

时间:2017-04-21 19:56:02

标签: python multithreading python-2.7 pyqt python-multithreading

我是PyQTQThread的新手。我的PyQT程序有一个按钮,可以每秒触发连续写入/读取串口。

问题:单击按钮并开始循环时,GUI会冻结。我错误地使用了QThread吗?

import sys
from PyQt4.QtGui import *
from PyQt4 import QtCore    
import serial
import time

from TemperatureReader import TemperatureReader # my module to talk to serial hardware


class Screen(QMainWindow):
    def __init__(self):
        super(Screen, self).__init__()
        self.initTemperatureReader()
        self.initUI()


    def initTemperatureReader(self):
        ser = serial.Serial(port='COM9', baudrate=115200, timeout=5)
        self.temperatureReader = TemperatureReader(ser)


    def initUI(self):
        startReadingTCsBtn = QPushButton('Start Reading')
        startReadingTCsBtn.clicked.connect(self.startReadingTCsThread)
        startReadingTCsBtn.show()

        directControlBoxLayout = QVBoxLayout()
        directControlBoxLayout.addWidget(startReadingTCsBtn)
        self.mainFrame = QWidget()
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(directControlGroupBox)
        self.mainFrame.setLayout(mainLayout)
        self.setCentralWidget(self.mainFrame)
        self.setGeometry(300,300,400,150)
        self.show()


    def startReadingTCsThread(self):
        self.tcReaderThread = TCReaderThread(self.temperatureReader)
        self.tcReaderThread.temperatures.connect(self.onTemperatureDataReady)
        self.tcReaderThread.start()

    def onTemperatureDataReady(self, data):
        print data



class TCReaderThread(QtCore.QThread):
    temperatures = QtCore.pyqtSignal(object)

    def __init__(self, temperatureReader):
        QtCore.QThread.__init__(self)
        self.temperatureReader = temperatureReader

    def run(self):
        while True:
            resultString = self.temperatureReader.getTemperature()  # returns a strng
            self.temperatures.emit(resultString)
            time.sleep(1)



def main():
    app = QApplication(sys.argv)
    screen = Screen()
    app.exec_()



if __name__ == '__main__':
    main()

0 个答案:

没有答案