3

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)
2
  • 1
    Have a look here, you might find your answer : gis.stackexchange.com/a/111405/25139
    – gisnside
    Sep 17, 2017 at 16:52
  • 1
    I think you may need to do something to set your progress in percentage unit - just my instinct saying that.
    – gisnside
    Sep 17, 2017 at 16:54

1 Answer 1

9

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

1
  • @nickan - Most welcome! Glad it helped :)
    – Joseph
    Sep 18, 2017 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.