QTextEdit.find() 在 Python 中不起作用

2024-05-13

演示问题的简单代码:

#!/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.

哪里有问题?


问题是光标在窗口中的位置。

默认情况下 - 除非您指定一些flags http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtextdocument.html#FindFlag-enum传递给find()函数,搜索只会发生forward(= 从光标位置开始)。

为了使你的测试工作,你应该这样做:

  1. 运行程序。
  2. 转到窗口并输入BA
  3. 将光标移至行首
  4. Type C

这样你就会在窗口中看到字符串CBA,光标位于C and B以及其上的字符串find()方法将返回TrueBA.

或者,您可以测试设置了向后标志的代码的其他版本。

#!/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_())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

QTextEdit.find() 在 Python 中不起作用 的相关文章