問題描述:
PyQt進行界面顯示使用的主線程,
如果程序中出現大量的運算,一直佔用主線程,會造成界面顯示卡死或者強制退出。
舉個例子:
沒有使用多線程:
# coding=utf-8
__author__ = 'a359680405'
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
global sec
sec=0
def setTime():
global sec
sec+=1
lcdNumber.display(sec) #LED顯示數字+1
def work():
timer.start(1000) #計時器每秒計數
for i in range(2000000000):
pass
timer.stop()
app=QApplication([])
top=QWidget()
layout=QVBoxLayout(top) #垂直佈局類QVBoxLayout;
lcdNumber=QLCDNumber() #加個顯示屏
layout.addWidget(lcdNumber)
button=QPushButton("測試")
layout.addWidget(button)
timer=QTimer()
timer.timeout.connect(setTime) #每次計時結束,觸發setTime
button.clicked.connect(work)
top.show()
app.exec()
上述例子沒有調用多線程,點擊按鈕之後計時器應該累加,但程序進入循環語句之後,一直在循環語句中出不來,導致顯示界面卡死。
改進:使用多線程
# coding=utf-8
__author__ = 'a359680405'
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
global sec
sec=0
class WorkThread(QThread):
trigger = pyqtSignal()
def __int__(self):
super(WorkThread,self).__init__()
def run(self):
for i in range(203300030):
print(i)
self.trigger.emit() #循環完畢後發出信號
def countTime():
global sec
sec+=1
lcdNumber.display(sec) #LED顯示數字+1
def work():
timer.start(1000) #計時器每秒計數
workThread.start() #計時開始
workThread.trigger.connect(timeStop) #當獲得循環完畢的信號時,停止計數
def timeStop():
timer.stop()
print("運行結束用時",lcdNumber.value())
global sec
sec=0
app=QApplication([])
top=QWidget()
layout=QVBoxLayout(top) #垂直佈局類QVBoxLayout;
lcdNumber=QLCDNumber() #加個顯示屏
layout.addWidget(lcdNumber)
button=QPushButton("測試")
layout.addWidget(button)
timer=QTimer()
workThread=WorkThread()
button.clicked.connect(work)
timer.timeout.connect(countTime) #每次計時結束,觸發setTime
top.show()
app.exec()
上述程序,將循環語句的計算部分放到新打開的線程裏面計算,不會造成界面卡死。
注意:
1、pyqt
界面顯示需要使用Qtime
,計算部分可調用多線程。
2、pyqtgraph
界面顯示同上。