4

I have a question regarding adding a warning popup when a user pressed OK while forgetting to fill in all the required fields in the plugin dialog. I have the following definition which checks if all fields contain text:

def inputCheck(self):
    if self.dlg.lineEdit_dxf.text() == "":
        QMessageBox.information(None, "Warning!", "Select a .dxf file" )
        return False
    return True

I thought that by adding the following code (see below) in the "def run(self)" part of the script the dialog would not close when the user presses OK. However, while the popup works fine and the script does not run, the dialog still closes down.

def run(self):
    self.dlg.show()
    result = self.dlg.exec_()
    if result:
        if not self.inputCheck():
            return

        #rest of script#

I built my plugin with the help of the plugin builder and I have not changed the overall layout of the script.

1 Answer 1

3

You need to overwrite the dialog's accept() method to be able to validate values before the dialog is actually accepted.

Go to the dialog Python file and add an accept() method at the end of the file, at the same indentation level as the constructor __init__( self ):

def accept( self ):
    validInput = self.inputCheck()
    if validInput:
       self.done( 1 ) # Only accept the dialog if all inputs are valid

As accept() needs to call inputCheck(), it makes sense to move your inputCheck() function into the dialog Python file. Just keep in mind that you won't need the self.dlg object, since you can access the dialog controls directly from the self object:

def inputCheck(self):
    if self.lineEdit_dxf.text() == "":
        QMessageBox.information(None, "Warning!", "Select a .dxf file" )
        return False
    return True

Note 1: You don't need to modify the original run() method in the plugin's main Python file, i.e., leave it as it was when created.

Note 2: Instead of showing a modal message box that blocks the entire application, you could show a Message Bar inside your plugin's dialog. See PyQGIS Cookbook for details.

4

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.