Python 如何选择QTextEdit段落?
大家好,谢谢你们抽出时间,我需要在cursorPositionChanged或selectionChanged上逐点选择一个完整且正确的段落,但我目前无法使用Python+Qt4,我尝试使用cursor.position和cursor.blockUndersor,QString的函数indexOf和lastIndexOf用于定位下一个点和上一个点以计算段落部分,但总是失败。 希望你能帮助我。 当做Python 如何选择QTextEdit段落?,python,qt,qtextedit,Python,Qt,Qtextedit,大家好,谢谢你们抽出时间,我需要在cursorPositionChanged或selectionChanged上逐点选择一个完整且正确的段落,但我目前无法使用Python+Qt4,我尝试使用cursor.position和cursor.blockUndersor,QString的函数indexOf和lastIndexOf用于定位下一个点和上一个点以计算段落部分,但总是失败。 希望你能帮助我。 当做 洛德福德。文本从一个点到另一个点的片段称为句子,而不是段落。下面是一个工作示例,请参见注释: im
洛德福德。文本从一个点到另一个点的片段称为句子,而不是段落。下面是一个工作示例,请参见注释:
import sys
from PyQt4 import QtCore, QtGui
class Example(QtGui.QTextEdit):
def __init__(self):
super(Example, self).__init__()
self.cursorPositionChanged.connect(self.updateSelection)
self.selectionChanged.connect(self.updateSelection)
self.setPlainText("Lorem ipsum ...")
self.show()
def updateSelection(self):
cursor = self.textCursor() # current position
cursor.setPosition(cursor.anchor()) # ignore existing selection
# find a dot before current position
start_dot = self.document().find(".", cursor, QtGui.QTextDocument.FindBackward)
if start_dot.isNull(): # if first sentence
# generate a cursor pointing at document start
start_dot = QtGui.QTextCursor(self.document())
start_dot.movePosition(QtGui.QTextCursor.Start)
# find beginning of the sentence (skip dots and spaces)
start = self.document().find(QtCore.QRegExp("[^.\\s]"), start_dot)
if start.isNull(): # just in case
start = start_dot
# -1 because the first (found) letter should also be selected
start_pos = start.position() - 1
if start_pos < 0: # if first sentence
start_pos = 0
#find a dot after current position
end = self.document().find(".", cursor)
if end.isNull(): # if last sentence
# generate a cursor pointing at document end
end = QtGui.QTextCursor(self.document())
end.movePosition(QtGui.QTextCursor.End)
cursor.setPosition(start_pos) #set selection start
#set selection end
cursor.setPosition(end.position(), QtGui.QTextCursor.KeepAnchor)
self.blockSignals(True) # block recursion
self.setTextCursor(cursor) # set selection
self.blockSignals(False)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
伟大的Thx Pavel对于你的回答,也许我的问题不清楚,但我已经看过你的代码,我一到我的位置就会测试它,我只是想说清楚,用户可以选择一个包含几个句子的区域,然后我会计算正确的段落扩展,从一个段落的点到点,而不是句子,理解?。太多了!!!对不起,我的英语不是我的主要语言