Search code examples
pythonpyqttypeerrorflagsqtextedit

How to initialise QTextEdit find options


I am trying to set the options in the following call:

bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags())

But the signature of option is complicated for a Python programmer. I tried the following:

option = 0
option = option | QTextDocument.FindBackward
# continue to check other checkboxes and build up the option this way

Unfortunately, the error is that 'int' is unexpected. I understand that since the option=0, then the following OR operation probably didn't yield an int type as well. But how to get a the proper starting null/unset/zero value?


Solution

  • The error is caused by a minor bug that occasionally appears in PyQt. If you update to the latest version, the error will probably go away. However, if you can't update, or if you want to bullet-proof your code against this problem, a work-around is to initialise the variable like this:

    >>> option = QTextDocument.FindFlag(0)
    >>> option = option | QTextDocument.FindBackward
    

    This will now guarantee that option has the expected type. The correct flag to use can be found by explicitly checking the type of one of the enum values:

    >>> print(type(QTextDocument.FindBackward))
    <class 'PyQt5.QtGui.QTextDocument.FindFlag'>
    

    Or you can just look up the relevant enum in the docs: QTextDocument.