Guest User

Untitled

a guest
Jul 12th, 2013
116
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import sys, time
  2. from PyQt4 import QtCore, QtGui
  3.  
  4. class MyApp(QtGui.QWidget):
  5.  def __init__(self, parent=None):
  6.   QtGui.QWidget.__init__(self, parent)
  7.  
  8.   self.setGeometry(300, 300, 280, 600)
  9.   self.setWindowTitle('threads')
  10.  
  11.   self.layout = QtGui.QVBoxLayout(self)
  12.  
  13.   self.testButton = QtGui.QPushButton("test")
  14.   self.connect(self.testButton, QtCore.SIGNAL("released()"), self.test)
  15.   self.listwidget = QtGui.QListWidget(self)
  16.  
  17.   self.layout.addWidget(self.testButton)
  18.   self.layout.addWidget(self.listwidget)
  19.  
  20.  def add(self, text):
  21.   """ Add item to list widget """
  22.   print "Add: " + text
  23.   self.listwidget.addItem(text)
  24.   self.listwidget.sortItems()
  25.  
  26.  def addBatch(self, text="test", iters=6, delay=0.3):
  27.   """ Add several items to list widget """
  28.   for i in range(iters):
  29.    time.sleep(delay)  # artificial time delay
  30.    self.add(text + " " + str(i))
  31.  
  32.  def threadFunc(self) :
  33.   print 'in threadFunc'
  34.  
  35.  def test(self):
  36.   self.listwidget.clear()
  37.   ## adding entries just from main application: locks ui
  38.   #self.addBatch("_non_thread", iters=6, delay=0.3)
  39.  
  40.   ## adding by emitting signal in different thread
  41.   #self.workThread = WorkThread()
  42.   #self.connect( self.workThread, QtCore.SIGNAL("update(QString)"), self.add )
  43.   #self.workThread.start()  
  44.  
  45.   self.genericThread = GenericThread(self.addBatch,"from generic thread ",delay=0.3)
  46.   #self.genericThread = GenericThread()
  47.   self.genericThread.start()  
  48.  
  49.   self.thread2=GenericThread(self.threadFunc)
  50.  
  51. #class WorkThread(QtCore.QThread):
  52.  #def __init__(self):
  53.   #QtCore.QThread.__init__(self)
  54.  
  55.  #def run(self,x):
  56.   #print x
  57.   #for i in range(6):
  58.    #time.sleep(0.3) # artificial time delay
  59.    #self.emit( QtCore.SIGNAL('update(QString)'), "from work thread " + str(i) )
  60.   #return
  61.  
  62.  
  63. class GenericThread(QtCore.QThread):
  64.  def __init__(self, function, *args, **kwargs):
  65.   QtCore.QThread.__init__(self)
  66.   self.function = function
  67.   self.args = args
  68.   self.kwargs = kwargs
  69.   print '='*50
  70.   print function
  71.   print args
  72.   print kwargs
  73.  
  74.  
  75.  def __del__(self):
  76.   self.wait()
  77.  
  78.  def run(self,x):
  79.   self.function(*self.args,**self.kwargs)
  80.   return  
  81.  
  82. # run
  83. app = QtGui.QApplication(sys.argv)
  84. test = MyApp()
  85. test.show()
  86. app.exec_()
RAW Paste Data