Search code examples
pythonpyqtpyqt4qgis

What's the best way to use a QMessageBox and return back to main form after clicking OK in PyQt?


I'm using a QMessageBox to tell the user if a field they entered is incorrect or missing before submitting the main form which triggers the run. Currently when the QMessageBox pops up, the main window disappears (I thought it would stay behind it but modal) and when you click OK, the whole application closes. I've looked at examples, but I can't tell what I'm doing wrong. Could someone please help?

Here's this piece of the code:

def isComplete(self):
  complete = True

  # check field
  variable = self.dlg.ui.txtField.text()

  if variable:
     # got a non-empty string
  else:
     complete = False
     msgBox = QtGui.QMessageBox()
     msgBox.setText("Please fill in all required fields")
     msgBox.exec_()

  return complete


def run(self):
  # show dialog
  self.dlg.show()

  # run the dialog event loop
  result = self.dlg.exec_()

  # check necessary fields
  complete = self.isComplete()

  # see if OK was pressed and fields are complete
  if (result and complete):
     self.runCalcs()

Solution

  • In simple cases you can use static methods information, question, warning and critical of QMessageBox. It will be modal if parent arg is specified:

    def isComplete(self):
      complete = True
    
      # check field
      variable = self.dlg.ui.txtField.text()
    
      if variable:
         # got a non-empty string
      else:
         complete = False
         QtGui.QMessageBox.warning(self, "Warning", "Please fill in all required fields")
    
      return complete
    
    
    def run(self):
      # show dialog
      self.dlg.show()
    
      # run the dialog event loop
      result = self.dlg.exec_()
    
      # check necessary fields
      complete = self.isComplete()
    
      # see if OK was pressed and fields are complete
      if (result and complete):
         self.runCalcs()