The PyQt4 code porting of《C++ GUI Programming with

Chapter 14. Multithreading

eg1

import sys, time from PyQt4.QtCore import * from PyQt4.QtGui import * class Thread(QThread): def __init__(self ): QThread.__init__(self) self.stopped = False; def setMessage(self, message): self.messageS = message def stop(self): self.stopped = True; def run(self): while self.stopped==False: print(self.messageS); time.sleep(1) self.stopped = False; print() class ThreadDialog(QDialog): def __init__(self, parent=None): super(ThreadDialog, self).__init__(parent) self.threadA=Thread () self.threadB=Thread () self.threadA.setMessage("A"); self.threadB.setMessage("B"); self.threadAButton = QPushButton(("Start A")); self.threadBButton = QPushButton(("Start B")); quitButton = QPushButton(("Quit")); quitButton.setDefault(True) self.threadAButton.clicked.connect(self.startOrStopThreadA); self.threadBButton.clicked.connect(self.startOrStopThreadB); quitButton.clicked.connect(self.close); mainLayout = QHBoxLayout() mainLayout.addWidget(self.threadAButton); mainLayout.addWidget(self.threadBButton); mainLayout.addWidget(quitButton); self.setLayout(mainLayout); self.setWindowTitle(("Threads")); def closeEvent(self, event): self.threadA.stop(); self.threadB.stop(); self.threadA.wait(); self.threadB.wait(); event.accept(); def startOrStopThreadA(self): if (self.threadA.isRunning()) : self.threadA.stop(); self.threadAButton.setText(("Start A")); else : self.threadA.start(); self.threadAButton.setText(("Stop A")); def startOrStopThreadB(self): if (self.threadB.isRunning()) : self.threadB.stop(); self.threadBButton.setText(("Start B")); else : self.threadB.start(); self.threadBButton.setText(("Stop B")); if __name__ == '__main__': app = QApplication(sys.argv) dialog=ThreadDialog() dialog.show() sys.exit(app.exec_())

 

评论

© ID4333709 | Powered by LOFTER