QTextedit find ()는 항상 False를 반환합니다 (pyside2).

Dec 10 2020

QTextEdit에서 검색하고 바꾸고 싶지만 QTextEdit.find ()는 항상 False를 반환하거나 아무것도 찾지 않습니다. 내 실수는 어디에 있습니까?

다음은 (매우) 최소한의 재현 가능한 예입니다.

from PySide2.QtWidgets import QApplication, QTextEdit
from PySide2.QtGui import QTextCursor
import sys

app = QApplication(sys.argv)
textedit = QTextEdit()
cursor = textedit.textCursor()
cursor.insertText("test test test")
cursor.movePosition(QTextCursor.Start)
print(textedit.find("t"))
textedit.show()
app.exec_()

Thx for that -.- : "이 질문에는 이미 답변이 있습니다. QTextEdit.find ()는 Python에서 작동하지 않습니다."

그것은 사실이 아닙니다. (아마도 그런 것을 말하고 질문을 닫기 전에 질문과 답변을 읽어보십시오. 이것이 stackoverflow가 그렇게 나쁜 평판을 갖는 이유입니다.) : "문제는 창에서 커서의 위치입니다. 기본적으로 검색은 앞으로 만 발생합니다. (= 커서 위치부터).하지만 커서를 커서를 문서의 시작 부분으로 설정했습니다. cursor.movePosition (QTextCursor.Start)

답변

1 furas Dec 10 2020 at 22:12

textedit.textCursor()위치의 로컬 사본 을 생성하고에서 원래 위치를 변경하지 않는 것으로 나타났습니다 QTextEdit.

QTextEdit사용시 위치를 업데이트해야합니다.

textedit.setTextCursor(cursor) 

find()처음으로 발견 할 것이다 t당신이 예상대로.


from PySide2.QtWidgets import QApplication, QTextEdit
from PySide2.QtGui import QTextCursor
import sys

app = QApplication(sys.argv)

textedit = QTextEdit()

cursor = textedit.textCursor()   # get local copy
cursor.insertText("test test test")
cursor.movePosition(QTextCursor.Start)
textedit.setTextCursor(cursor)   # update it

#textedit.insertPlainText("test test test")
#textedit.moveCursor(QTextCursor.Start)

textedit.show()

print(textedit.find("t"))  # first `t`
print(textedit.find("t"))  # second `t`

app.exec_()