4

I try to use a custom-form in QGIS 3 to validate input-data before saving the data in a database. It would be nice to have the form open unless every input is correct. But the dialog/form closes even if the code detects wrong data...

...
my_dialog = None
inputField = None

def form_open(dialog, layerid, featureid):
    global my_dialog
    my_dialog=dialog

    global inputField
    inputField = my_dialog.findChild(QLineEdit,"qle_input")

    buttonBox = my_dialog.findChild(QDialogButtonBox,"buttonBox")

    buttonBox.accepted.disconnect()

    buttonBox.accepted.connect(validate)

    buttonBox.rejected.connect(my_dialog.resetValues)


def validate():
    inputString=inputField.text() # get text from qleInput
    pattern = re.compile("[^A-Za-z0-9]"); #pattern of not allowed data
    if re.findall(pattern,inputString): 
        #if match (wrong characters) - give a warning and let the dialog open to change text in qle_input
        textString='<b><center> Input contains wrong characters </center></b>'
        msgBox = QMessageBox()
        msgBox.setText(textString)
        msgBox.exec_()
    else: # Close dialog
        my_dialog.close
  • I can't help but Nathan Woodrow did a nice explanation on how to do that (You may need to do some adjustment for it to work with QGIS 3) : nathanw.net/2011/09/05/… – J.R Nov 26 '19 at 12:15
  • Thanks, I know this explanation, but as it refers to an old qgis/pyqgis/pyqt-version...i didn't manage to make every adjustment in a correct way – user191847 Nov 26 '19 at 12:50
1

My solution (with some additonal adjustments to names) is:

from qgis.core import *
from qgis.gui import *
from PyQt5.QtWidgets import QLineEdit, QMessageBox, QDialogButtonBox
import re
from qgis.utils import iface

my_dialog = None
hausNr = None

def form_open(dialog, layerid, featureid):

    global my_dialog 
    my_dialog=dialog 
    global hausNr 
    hausNr = my_dialog.findChild(QLineEdit,"haus_nr") 
    hausNr.textChanged.connect(check_hausNr)

    global buttonBox
    buttonBox = my_dialog.findChild(QDialogButtonBox,"buttonBox")

def check_hausNr():
    buttonBox.button(buttonBox.Ok).setEnabled(False)
    hausNrText=hausNr.text()

    pattern = re.compile("[^A-Za-z0-9]");
    listWrongText=re.findall(pattern,hausNrText)
    warning="'"+", ".join(listWrongText)+"'"
    if listWrongText: 
        iface.messageBar().pushMessage("Wrong characters:", warning, level=Qgis.Critical, duration=3)
        hausNr.setStyleSheet("background-color: rgba(255, 150, 150, 100);")
        buttonBox.button(buttonBox.Ok).setEnabled(False)
    else:
        buttonBox.button(buttonBox.Ok).setEnabled(True)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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