QTextEdit.find() 在 Python 中不起作用 [英] QTextEdit.find() doesn't work in Python

查看:115
本文介绍了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.

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

问题出在哪里?

推荐答案

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

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

默认情况下 - 除非您指定一些 标志 传递给 find() 函数,搜索只发生forward(= 从光标位置开始).

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. 运行程序.
  2. 转到窗口并输入BA
  3. 将光标移动到行首
  4. 输入C

这样,您将在窗口中看到字符串 CBA,光标位于 CB 之间,以及 CBA 所在的字符串code>find() 方法将工作返回 True 将是 BA.

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_())

这篇关于QTextEdit.find() 在 Python 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆