PyQt处理导致GUI延迟
我正在用Python写一个Qt应用程序,这个程序会处理一个txt文件。用户可以从他们的硬盘上选择一个文件,然后程序会打开并处理它。现在我遇到的主要问题是,第一次运行程序时一切正常;但是如果不重启程序就多次运行,每次运行的时间都是一样的,但进度条却会卡顿,有时候文件选择对话框在处理完成之前不会消失。下面是我的代码。我知道缩进有问题,因为复制的时候没有正确显示。有没有人能看出是什么原因导致第一次运行后会出现卡顿的情况?
import sys, time, os
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(QtGui.QMainWindow):
def updateProgress(self):
self.progressBar.setValue(self.progressBar.value()+1)
self.progressBar.repaint()
def processCollect(self):
filename = None
self.progressBar.setValue(0)
#Get the filename from user
try:
filename = QtGui.QFileDialog.getOpenFileName(self, "Open Collect", sys.path[1] + "/", "Text files (*.txt)")
except IOError:
filename == None
if filename:
#Find number of lines
file = open(filename, "r")
linecount = 0
for line in file:
linecount = linecount+1
file.close()
print(linecount)
#Set up progress bar
self.progressBar.setMinimum(0)
self.progressBar.setMaximum(linecount)
self.progressBar.show()
#Read file contents and update progress bar
file = open(filename, "r")
for line in file:
line = line.replace("\n", "")
print(line)
time.sleep(.05)
self.updateProgress()
file.close()
def setupUi(self, MainWindow):
#Create the main window
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
#Body of the main window
self.centralwidget = QtGui.QWidget(MainWindow)
#Add process collect button
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.centralwidget.buttonProcessCollect = QtGui.QPushButton(self.centralwidget)
self.centralwidget.buttonProcessCollect.setGeometry(QtCore.QRect(310, 240, 120, 40))
self.centralwidget.buttonProcessCollect.setObjectName(_fromUtf8("buttonProcessCollect"))
#Add progress bar
self.progressBar = QtGui.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(165, 290, 430, 20))
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.progressBar.hide()
#Add actions to body
self.centralwidget.connect(self.centralwidget.buttonProcessCollect, SIGNAL("clicked()"), self.processCollect)
#Add body to the menu
MainWindow.setCentralWidget(self.centralwidget)
#Add text
self.retranslateUi(MainWindow)
#Connect actions
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
self.centralwidget.buttonProcessCollect.setText(QtGui.QApplication.translate("MainWindow", "Process Collect", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
1 个回答
2
这个问题可以通过使用线程来解决,这样实际的用户界面就不会受到影响。
你可以使用 Python 的线程模块或者 Qt 的 QThread 模块。
Twio 提到了这个话题:
这里有一个关于在 PyQt 中使用线程的教程: PyQt4 线程教程