当使用python pyqt时,我制作了一个Qprogressbar,并使用Q线程更新了数字。下面显示的代码在第一次就成功了,再运行一次就会崩溃。
这是针对Python PyQt5的,在Python 3.5系统中。我尝试将进度条重置为 0,但似乎不正确
这是我点击加载文件按钮后的调用函数,加载文件按钮和进度条位于QtWidgets.Qmainwindows中
loading_event_name = QtWidgets.QFileDialog.getOpenFileNames(self, 'CSV File', 'C:\', '*.csv')
self.loading_progress_bar.reset()
self.loading_thread = QThread()
self.loading_worker = Load_Task_Thread()
self.loading_worker.moveToThread(self.loading_thread)
self.loading_thread.started.connect(self.loading_worker.run)
self.loading_thread.start()
self.loading_worker.Load_taskFinished.connect(self.Load_onFinished)
self.loading_worker.Loading_progressChanged.connect(self.loading_progress_bar.setValue, Qt.QueuedConnection)'''
第一个加载文件线程将完美运行,但是如果我想加载新文件,则下次单击,软件将崩溃,线程未更新,进度条不像第一次那样更新数字,并且自重置以来保持零。在调试模式下,我也无法向进度条发出任何数字:
class Load_Task_Thread(QThread):
Load_taskFinished = pyqtSignal()
Loading_progressChanged = pyqtSignal(int)
def run(self):
progress = 0
for file_name_num in range(len(loading_event[0])):
progress = 90 * file_name_num/len(loading_event_name[0])
self.Loading_progressChanged.emit(progress)
1+1.....
self.Loading_progressChanged.emit(100)
self.Load_taskFinished.emit()
我希望无论单击多少次选择新文件,都可以更新进度条。或者是否有任何其他简单的方法可以显示进度条以显示加载过程。
您可能还有其他错误,但从您提供的代码中,我观察到以下错误:
你已经创建了一个QThread(Load_Task_Thread(,并且你已经把它移动到另一个QThread,这是不必要的,因为Load_Task_Thread是一个QObject就足够了。
没有必要在每次启动进程时都创建 QThread,因为驻留在线程中的 QObject 就足够了。
考虑到上述情况,我实现了以下示例:
from functools import partial
from PyQt5 import QtCore, QtGui, QtWidgets
class Load_Task_Worker(QtCore.QObject):
started = QtCore.pyqtSignal()
finished = QtCore.pyqtSignal()
progressChanged = QtCore.pyqtSignal(int)
@QtCore.pyqtSlot(list)
def run(self, filenames):
total = len(filenames)
self.started.emit()
self.progressChanged.emit(0)
for i, filename in enumerate(filenames, 1):
# start process
# ...
# end process
progress = 100 * i // total
self.progressChanged.emit(progress)
self.finished.emit()
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.button = QtWidgets.QPushButton("Start Task")
self.loading_progress_bar = QtWidgets.QProgressBar()
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.button)
lay.addWidget(self.loading_progress_bar)
thread = QtCore.QThread(self)
thread.start()
self.worker = Load_Task_Worker()
self.worker.moveToThread(thread)
self.button.clicked.connect(self.onClicked)
self.worker.progressChanged.connect(self.loading_progress_bar.setValue)
self.worker.finished.connect(self.onFinished)
@QtCore.pyqtSlot()
def onFinished(self):
self.button.setEnabled(True)
@QtCore.pyqtSlot()
def onClicked(self):
filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(
self, "CSV File", "C:\", "*.csv"
)
if filenames:
self.button.setEnabled(False)
self.loading_progress_bar.reset()
wrapper = partial(self.worker.run, filenames)
QtCore.QTimer.singleShot(0, wrapper)
else:
print("not selected files")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())