QValidator.State TypeError

Florian Bruhin me at the-compiler.org
Wed Jun 14 16:37:21 BST 2023


Hey,

> When implementing my own subclass of QValidator, I get a "TypeError:
> invalid result from Validator.validate()" error followed by a segfault on
> macOS for the following code:
> 
> Example:
> 
> [...]
> 
> class Validator(QtGui.QValidator):
> 
>     def validate(self, index_, pos):
>         return QtGui.QValidator.State.Acceptable

This should return (QtGui.QValidator.State.Acceptable, index_, pos)
instead.

> Running this file generates a QLineEdit, but the moment you edit the
> contents and have the widget lose focus the following error is emitted:
> 
> TypeError: invalid result from Validator.validate()

That's correct. This is one of the instances where Qt in C++ expects you
(or at least allows you) to modify the contents of one of the references
given as arguments:

https://doc.qt.io/qt-6/qvalidator.html#validate
"The function can change both input and pos (the cursor position) if
required."

However, in Python, this isn't possible (both str and int are
immutable), so PyQt solves this by returning a
tuple[QValidator.State, str, int] instead. See help() in Python:

    >>> help(QValidator.validate)
    Help on built-in function validate:

    validate(...) method of PyQt6.sip.wrappertype instance
        validate(self, a0: str, a1: int) -> Tuple[QValidator.State, str, int]

or the PyQt docs:
https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtgui/qvalidator.html

Florian
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20230614/14d42dc1/attachment.sig>


More information about the PyQt mailing list