2015-10-14 71 views
0

多線程Pyside應用程序的最簡單方法是什麼?所以GUI可以運行,線程仍然可以運行? Thread類:如何編寫多線程的Pyside應用程序

class MyLongThread(QThread): 
     def __init__(self, parent = None): 
      QThread.__init__(self, parent) 
      self.exiting = False 

     def run(self): 
      while 1: 
       self.msleep(100) 
       print("run") 

完全.pyw

import sys,time 
from PySide.QtGui import * 
from PySide.QtCore import * 
from PySide.QtWebKit import * 
def thread(): 
    global threade 
    threade = MyLongThread() 
    threade.run() 

def thread_terminate(): 
    global threade 
    threade.terminate()  

class MyLongThread(QThread): 
     def __init__(self, parent = None): 
      QThread.__init__(self, parent) 
      self.exiting = False 

     def run(self): 
      while 1: 
       self.msleep(100) 
       print("run") 
app = QApplication(sys.argv) 

wid = QWidget() 
wid.resize(250, 400) 
wid.setWindowTitle('Threaded Program') 
#wid.setWindowIcon(QIcon('web.png')) 
#### BUTTONS 
btn = QPushButton('Stop', wid) 
btn.setToolTip('Stop the thread.') ## Stop the thread 
btn.resize(btn.sizeHint()) 
btn.move(147, 50) 
btn.clicked.connect(thread_terminate) 
qbtn = QPushButton('Start', wid) 
qbtn.setToolTip('Start the thread.') ## End the Thread 
qbtn.resize(btn.sizeHint()) 
qbtn.move(27, 50) 
qbtn.clicked.connect(thread) 
#### 


#### LABEL 
label = QLabel('Start The Thread :)',wid) 
label.resize(label.sizeHint()) 
label.move(28, 15) 
#### 

wid.show() 

sys.exit(app.exec_()) 

當我運行的代碼,並按下啓動按鈕,它凍結的GUI,但打印運行。

回答

1

不要直接調用thread.run(),因爲這會在主線程中執行該方法。相反,調用thread.start()將啓動一個線程,並開始在線程中執行run()方法。