大家好,感谢您的时间,我需要在cursorPositionChanged()或selectionChanged()上选择一个完整且正确的段落(从点到点)但是到目前为止我还不能用Python + Qt4来做,我尝试使用cursor.position()和cursor.BlockUnderCursor,QString的函数indexOf()和lastIndexOf()来定位下一个和前一个“点”来计算段落部分,但总是失败。 希望您能够帮助我。 问候。 LordFord。
答案 0 :(得分:0)
点到点的文本片段称为句子,而不是段落。这是一个有效的例子(见评论):
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()