Get visual feedback from QValidator
Asked Answered
C

3

6

I am trying to use QValidator descendants (actually in PyQt5, but that shouldn't matter) to validate a series of line-edits.

A small excerpt is:

class IPv4(QWidget):
    def __init__(self):
        super(IPv4, self).__init__()
        uic.loadUi('ipv4.ui', self)
        self.address.inputMask = ''
        rx = QRegularExpression(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
        self.address.setValidator(QRegularExpressionValidator(rx, self.address))
        self.netmask.setValidator(QRegularExpressionValidator(rx, self.netmask))
        self.gateway.setValidator(QRegularExpressionValidator(rx, self.gateway))
        self.broadcast.setValidator(QRegularExpressionValidator(rx, self.broadcast))
        self.dns1.setValidator(QRegularExpressionValidator(rx, self.dns1))
        self.dns2.setValidator(QRegularExpressionValidator(rx, self.dns2))
        self.on_dhcp_clicked(self.dhcp.isChecked())

This works as advertised, but the user gets no feedback, since trying to input "wrong" characters simply discards them.

I didn't find any way to give feedback beside hooking into the QLineEdit.textChanged signal and doing validation "manually" (i.e.: without setting a validator, otherwise on error text won't change and no signal will be emitted). The preferred feedback would be to change the line-edit's border-color.

This somehow defeats the purpose of the validator itself. It seems I'm missing something, since I can't see how to trigger feedback from QValidator.

What is the "standard way" to handle this?

Cheeseparing answered 7/10, 2019 at 23:57 Comment(0)
W
7

A custom signal can be used to indicate validation-state changes by reimplementing the validate method in a subclass. Below is a script that demonstrates this approach. (Note that the signature of validate is different in PyQt, because it does not mutate the arguments as in C++).

import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class RegExpValidator(QtGui.QRegularExpressionValidator):
    validationChanged = QtCore.pyqtSignal(QtGui.QValidator.State)

    def validate(self, input, pos):
        state, input, pos = super().validate(input, pos)
        self.validationChanged.emit(state)
        return state, input, pos

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        regexp = QtCore.QRegularExpression(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
        validator = RegExpValidator(regexp, self)
        validator.validationChanged.connect(self.handleValidationChange)
        self.edit = QtWidgets.QLineEdit()
        self.edit.setValidator(validator)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.edit)

    def handleValidationChange(self, state):
        if state == QtGui.QValidator.Invalid:
            colour = 'red'
        elif state == QtGui.QValidator.Intermediate:
            colour = 'gold'
        elif state == QtGui.QValidator.Acceptable:
            colour = 'lime'
        self.edit.setStyleSheet('border: 3px solid %s' % colour)
        QtCore.QTimer.singleShot(1000, lambda: self.edit.setStyleSheet(''))


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
Wiatt answered 8/10, 2019 at 11:16 Comment(0)
S
3

If you want to verify if the QLineEdit text is valid then you must use the hasAcceptableInput() method:

from PyQt5 import QtCore, QtGui, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        rx = QtCore.QRegularExpression(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")

        self.le = QtWidgets.QLineEdit()
        self.le.setValidator(QtGui.QRegularExpressionValidator(rx, self.le))
        self.le.textChanged.connect(self.on_textChanged)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.le)

    @QtCore.pyqtSlot()
    def on_textChanged(self):
        le = self.sender()
        if isinstance(le, QtWidgets.QLineEdit):
            le.setStyleSheet(
                "border: 5px solid {color}".format(
                    color="green" if le.hasAcceptableInput() else "red"
                )
            )


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = Widget()
    w.show()

    sys.exit(app.exec_())
Schinica answered 8/10, 2019 at 2:48 Comment(1)
As explained in OP this does not actually work. In normal operation QLineEdit.validator takes precedence, and thus on_textChanged() is not called at all on invalid input. Your code actually distinguish between Intermediate and Acceptable. Still no feedback (not even a beep) for truly Invalid entry. Side question: why did You edit tags? I don't think this is specific to pyqt; it looks like a design issue in original QValidator class.Cheeseparing
C
2

I accepted @ekhumoro answer as essentially correct, but I will also post my current test code which is (IMHO!) easier to maintain in the long run.

from __future__ import annotations

import typing

from PyQt5 import QtCore, QtGui, QtWidgets


class MyValidator(QtGui.QRegularExpressionValidator):
    def validate(self, text: str, pos: int) -> typing.Tuple[QtGui.QValidator.State, str, int]:
        state, text, pos = super(MyValidator, self).validate(text, pos)
        selector = {
            QtGui.QValidator.Invalid: 'invalid',
            QtGui.QValidator.Intermediate: 'intermediate',
            QtGui.QValidator.Acceptable: 'acceptable'
        }[state]

        if selector == 'invalid':
            sel = self.parent().property('selector')

            def restore():
                self.parent().setProperty('selector', sel)
                self.parent().setStyleSheet('/**/')
            QtCore.QTimer.singleShot(1000,  restore)
        self.parent().setProperty('selector', selector)
        self.parent().setStyleSheet('/**/')
        return state, text, pos


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.le = QtWidgets.QLineEdit()
        regexp = QtCore.QRegularExpression(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
        self.le.setValidator(MyValidator(regexp, self.le))
        self.le.setProperty('selector', 'none')

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.le)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setStyleSheet('''\
    *[selector="invalid"] {border-radius: 3px; border: 1px solid red;}
    *[selector="intermediate"] {border-radius: 3px; border: 1px solid gold;}
    *[selector="acceptable"] {border-radius: 3px; border: 1px solid green;}
    ''')

    w = Widget()
    w.show()

    sys.exit(app.exec_())

I have two (nitpick) problems with this code; but that is matter for another question ;)

Cheeseparing answered 8/10, 2019 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.