0

The following code is meant to update a progress bar as a 24line file is read. The timer serving to demonstrate what is going on in a longer time.

What actually happens is that the whole file is read line by line and then the progress bar is updated in one go at the end.

I am thinking that this a some kind of focus issue about the file dialog being open or a threading thing.

    for x in range(0, i):
          print ("We're on line",x)
          line=f.readline()
          time.sleep(0.3)
          self.ui.textEdit.append(line)
          self.ui.progressBar.setProperty("value", i*4)    
    f.close()

File dialog (which works)is

file_name = QFileDialog.getOpenFileName(self, "select file")

The complete code is below complete with print debugging mess

class MainWindow(QMainWindow):
def __init__(self):
    super(MainWindow, self).__init__()

    # Set up the user interface
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.ui.textEdit.setAlignment(QtCore.Qt.AlignLeft)
    self.ui.btn_load_data.clicked.connect(self.browse_for_file)
    self.show()

def browse_for_file(self):
    file_name = QFileDialog.getOpenFileName(self, "select file")
    i = 0
    print(file_name)
    self.ui.textEdit.append("Just going in")
    with open(file_name[0]) as file:
        for line in file:
            i += 1
    f = open(file_name[0], "r")
    print("lines in file is ",i)
    for x in range(0, i):
        print ("We're on line",x)
        line=f.readline()
        time.sleep(0.3)
        self.ui.textEdit.append(line)
        self.ui.progressBar.setProperty("value", i*4)    
    f.close()
app = QApplication(sys.argv)
window = MainWindow()
app.exec_()
nerak99
  • 640
  • 8
  • 26

1 Answers1

1

The problem happens because the user interface is drawn inside the event loop, and your code is not returning to the event loop. One way to process events while some function is running is to use QApplication.processEvents(), like:

for x in range(0, i):
      print ("We're on line",x)
      line=f.readline()
      time.sleep(0.3)
      self.ui.textEdit.append(line)
      self.ui.progressBar.setProperty("value", i*4)
      QApplication.processEvents()
f.close()

This will let events be processed, including the drawing of the user interface.

Dr. Snoopy
  • 55,122
  • 7
  • 121
  • 140