0

Hy,

I have a txt file I'm loading in a qt plain text interface widget (I'm working with python).

I define a "search" function, but I have a problem:

If the word I'm searching is upper than my last search, it find nothing. I have read that I have to put my cursor to the beginning of the text, but impossible to find an example, and all of my test are failure.

Here is my code:

def search_in_txt(self):
    txt_to_search = self.lineEdit.text()
    try:
        result = self.plainTextEdit_2.find(txt_to_search)

        if result == False:
            # move cursor to the beginning and restart search
            self.plainTextEdit_2.textCursor.movePosition(QTextCursor_MoveOperation=Start)
            self.plainTextEdit_2.find(txt_to_search)
    except:
        self.statusbar.showMessage("This is the last iteration founded")
    return

Thanx for your help, I'm getting crazy! Is there no option directly in the "find" function to restart from beginning when it arrive at the end of the document?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
lelorrain7
  • 315
  • 5
  • 13

2 Answers2

1

Ok, I got it! instead of textCursor.moveposition, it must be used this solution:

def search_in_txt(self):
    txt_to_search = self.lineEdit.text()
    try:
        result = self.plainTextEdit_2.find(txt_to_search)

        if result == False:
            # move cursor to the beginning and restart search
            self.plainTextEdit_2.moveCursor(QtGui.QTextCursor.Start)
            self.plainTextEdit_2.find(txt_to_search)
    except:
        self.statusbar.showMessage("This is the last iteration founded")
    return    
lelorrain7
  • 315
  • 5
  • 13
  • Cool, I think we were missing calling 'setTextCursor' as it seems that 'textCursor.movePosition' is operating on copy of cursor, not on cursor itself. Answer by limbo here https://stackoverflow.com/questions/6786641/problem-in-moving-qtextcursor-to-the-end has more info – Dolfa Oct 11 '19 at 13:12
0

I am not sure about restarting from beginning, but you can use flag to search backward. In your case:

if result == False:
        self.plainTextEdit_2.find(txt_to_search, QTextDocument.FindBackward)

Or try from the get go:

self.plainTextEdit_2.textCursor.movePosition(QTextCursor.Start)
self.plainTextEdit_2.find(txt_to_search)
Dolfa
  • 796
  • 4
  • 21
  • But in modifying a bit the first solution, it works: self.plainTextEdit_2.find(txt_to_search, QtGui.QTextDocument.FindBackward) It was missing the "QtGui." the solution with the start would be more elegant, because with the Findbackward solution, I cas fall in a loop between only two word. But when I do the same thing with the second solution : QtGui.QTextCursor.Start it is not working. any Idea why ? – lelorrain7 Oct 11 '19 at 12:20