Tuesday 10 January 2017

pyqgis - How to show a moving progress bar in QGIS


I want to sum values and during do it, a window shows progress percentage. I write below code but when I run it in qgis python console, qgis crashes. what is error in this code?


from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *


def progdialog(progress):
dialog = QProgressDialog()
dialog.setWindowTitle("Progress")
dialog.setLabelText("text")

bar = QProgressBar(dialog)
bar.setTextVisible(True)
bar.setValue(progress)
dialog.setBar(bar)

dialog.setMinimumWidth(300)
dialog.show()

def calc(x, y):
sum = 0
progress = 0
for i in range(x):
for j in range(y):
k = i + j
sum =+ k

progress =+1
progdialog(progress)
print sum

calc(10000, 2000)

Answer



I think there's a few minor issues:




  • You're using =+ which means you're setting it to equal a positive value. I think you meant to use += which adds and sets the new value to the variable.





  • Within your two for loops, you are calling the progdialog() function x*y times. Each time it is recreating the progress dialog and bar instead of updating it. I'm guessing this cause QGIS to crash.




  • As @gisnside mentioned, you need to set the progress values accordingly.






You could try using the following which calls the progdialog function once and returns the reference to the progress dialog and bar:



from PyQt4.QtGui import QProgressDialog, QProgressBar

def progdialog(progress):
dialog = QProgressDialog()
dialog.setWindowTitle("Progress")
dialog.setLabelText("text")
bar = QProgressBar(dialog)
bar.setTextVisible(True)
bar.setValue(progress)
dialog.setBar(bar)

dialog.setMinimumWidth(300)
dialog.show()
return dialog, bar

def calc(x, y):
dialog, bar = progdialog(0)
bar.setValue(0)
bar.setMaximum(100)
sum = 0
progress = 0

for i in range(x):
for j in range(y):
k = i + j
sum += k
i += 1
progress = (float(i) / float(x)) * 100
bar.setValue(progress)
print sum

calc(10000, 2000)


Result


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...