2017-05-28 210 views
0

如何在PyQt5中使用Python3異步調用方法?如何在PyQt5中使用Python3異步調用方法?

我試圖用信號來做到這一點。

import sys 
from time import sleep 

from PyQt5.QtCore import pyqtSignal 
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel 


class MainWindow(QMainWindow): 
    asyncFuncSignal = pyqtSignal() 

    def __init__(self): 
     super().__init__() 
     self.initUi() 

    def initUi(self): 
     self.label = QLabel(self) 
     self.label.setText("loading...") 

     # Trying to call 'self.asyncFunc' asynchronously 
     self.asyncFuncSignal.connect(self.asyncFunc) 
     self.asyncFuncSignal.emit() 

     print("loaded") 

    def asyncFunc(self): 
     # Doing something hard that takes time 
     # I have used 'sleep' to implement the delay 
     sleep(2) 

     self.label.setText("done") 
     print("asyncFunc finished") 


if __name__ == "__main__": 
    app = QApplication(sys.argv) 
    window = MainWindow() 
    window.show() 
    sys.exit(app.exec_()) 

此程序試圖寫"loaded"前完成asyncFunc。但我希望程序立即完成initUi,並在標籤中顯示loading...,之後文本done在2秒內出現。

什麼是最好的和最短的做法呢?

這裏說的是http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html我可以使用排隊連接,但我還沒有找到如何實現它的例子。

回答

0

PyQt5.QtCore.Qt.QueuedConnection可能會有所幫助。只需更換

self.asyncFuncSignal.connect(self.asyncFunc) 

from PyQt5.QtCore import Qt 

... 

self.asyncFuncSignal.connect(self.asyncFunc, Qt.QueuedConnection)