Search code examples
pythonqtqt4pyqt4qtextedit

QTextEdit.find() doesn't work in Python


Simple code demonstrating the problem:

#!/usr/bin/env python

import sys
from PyQt4.QtCore import QObject, SIGNAL
from PyQt4.QtGui import QApplication, QTextEdit

app = QApplication(sys.argv)

def findText():
    print(textEdit.find('A'))

textEdit = QTextEdit()
textEdit.show()
QObject.connect(textEdit, SIGNAL('textChanged()'), findText)
sys.exit(app.exec_())

After typing 'A' into the window, find('A') still returns False.

Where is the problem?


Solution

  • The problem is the position of the cursor in the window.

    By default - unless you specify some flags to be passed to the find() function, the search only happens forward (= from the position of the cursor onwards).

    In order to make your test work, you should do something like this:

    1. Run the program.
    2. Go to the window and type BA
    3. Move your cursor to the beginning of the line
    4. Type C

    This way you will have in the window the string CBA, with the cursor between C and B and the string onto which the find() method will work returning True will be BA.

    Alternatively you can test this other version of your code that has the backward flag set.

    #!/usr/bin/env python
    # -*- coding: utf-8  -*-
    
    import sys
    from PyQt4.QtCore import QObject, SIGNAL
    from PyQt4.QtGui import QApplication, QTextEdit, QTextDocument
    
    app = QApplication(sys.argv)
    
    def findText():
        flag = QTextDocument.FindBackward
        print(textEdit.toPlainText(), textEdit.find('A', flag))
    
    textEdit = QTextEdit()
    textEdit.show()
    QObject.connect(textEdit, SIGNAL('textChanged()'), findText)
    sys.exit(app.exec_())