我有一个简单的进度条,我想在循环中弹出,如下例所示。
我必须在应用程序之外实例化它,然后调整循环的值。为什么?我会认为在MainWindow中实例化一个新的进度条类是更理想的,但是没有显示出来。我认为它与app.exec
有关。但是,如果我为进度条添加self.exec
,它不会更新,那么实现它的正确方法是什么?
from PyQt5.Qt import *
import sys
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.centralwidget = QWidget(MainWindow)
self.pushButton = QPushButton(self.centralwidget)
self.pushButton.setText("CLICK ME")
MainWindow.setCentralWidget(self.centralwidget)
self.pushButton.clicked.connect(self.testloop)
def testloop(self):
n = 200
print(progressbar.wasCanceled())
progressbar.setMinimum(0)
progressbar.setValue(0)
progressbar.setMaximum(n)
progressbar.show()
for i in range(n):
progressbar.setValue(i)
if progressbar.wasCanceled(): # How can I un-cancel and reset the progress bar again?
break
class ProgressBar(QProgressDialog):
def __init__(self):
super().__init__()
self.setValue(0)
self.setModal(True)
def step(self, i):
self.setValue(i)
if __name__ == "__main__":
app = QApplication(sys.argv)
mainwindow = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(mainwindow)
mainwindow.show()
progressbar = ProgressBar() # Do I need to instantiate a progressbar here,
# or can I instantiate and kill it inside the app code?
sys.exit(app.exec_())
答案 0 :(得分:0)
简单实现循环的进度条:
from PyQt5.Qt import *
import sys
import time
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.centralwidget = QWidget(MainWindow)
self.pushButton = QPushButton(self.centralwidget)
self.pushButton.setText("CLICK ME")
MainWindow.setCentralWidget(self.centralwidget)
self.pushButton.clicked.connect(self.testloop)
def testloop(self):
n = 10
progressbar = ProgressBar(n, title = "Copying files...")
for i in range(n):
time.sleep(0.01)
progressbar.setValue(i)
if progressbar.wasCanceled():
break
class ProgressBar(QProgressDialog):
def __init__(self, max, title):
super().__init__()
self.setMinimumDuration(0) # Sets how long the loop should last before progress bar is shown (in miliseconds)
self.setWindowTitle(title)
self.setModal(True)
self.setValue(0)
self.setMinimum(0)
self.setMaximum(max)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
mainwindow = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(mainwindow)
mainwindow.show()
sys.exit(app.exec_())