[PyQt] thread in pyqt ... simple example needed

Hazen Babcock hbabcock at mac.com
Sun Apr 5 20:29:44 BST 2009


massimo di stefano wrote:

>  .. done little step ahead :
> 
> 
> import sys
> from PyQt4 import QtCore, QtGui
> import time
> 
> class MyThread(QtCore.QThread):
>     def run(self):
>         n = 0
>         step = 1
>         while True:
>             n += step
>             print n
> 
> 
> class Gui(QtGui.QWidget):
>     def __init__(self, parent=None):
>         QtGui.QGroupBox.__init__(self, parent)
>         self.gcenter = QtGui.QPushButton("X", self)
>         self.gcenter.setAutoRepeat(True)
>         guiLayout = QtGui.QGridLayout()
>         guiLayout.addWidget(self.gcenter,1,0)
>         self.setLayout(guiLayout)
>         self.thread = MyThread()
>         self.connect(self.gcenter, QtCore.SIGNAL("clicked()"), 
> self.thread.start)
> 
> 
> 
> if __name__ == "__main__":
>     app = QtGui.QApplication(sys.argv)
>     gui = Gui()
>     gui.show()
>     sys.exit(app.exec_())
> 
> 
> 
> now i need to stop it when i "release" the button,
> tried with :
> 
>         self.connect(self.gcenter, QtCore.SIGNAL("released()"), 
> self.thread.quit)
> 
> but give :
> 
> AttributeError: stop
> 

I'd suggest expanding your MyThread class to something like this:

class MyThread(QtCore.QThread):
     def __init__(self, parent = None):
         QtCore.QThread.__init__(self, parent)
         self.running = 1

      def run(self):
          n = 0
          step = 1
          while self.running:
              n += step
              print n
              self.msleep(100)

     def stop(self):
	 self.running = 0

You should also look at the QtCore.QMutex() class, which provides a way 
to synchronize (via locking) between the thread process and other processes.

-Hazen



More information about the PyQt mailing list