QTextEdit.find()在Python中不起作用
下面是一个简单的代码,展示了这个问题:
#!/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_())
在窗口里输入了'A'之后,find('A')
仍然返回 False
。
问题出在哪里呢?
1 个回答
4
问题出在光标在窗口中的位置。
默认情况下,除非你给 find()
函数传递一些特定的 标志,否则搜索只会向前进行,也就是从光标当前位置开始往后找。
为了让你的测试能够正常工作,你可以按照以下步骤操作:
- 运行程序。
- 在窗口中输入
BA
- 把光标移动到这一行的开头
- 输入
C
这样,你在窗口中就会看到字符串 CBA
,光标在 C
和 B
之间,而 find()
方法要查找的字符串是 BA
,这时返回的结果会是 True
。
另外,你也可以测试另一种设置了向后查找标志的代码版本。
#!/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_())