Hello everyone and thanks for your time, I need to select a entire and correct paragraph (from dot to dot) on cursorPositionChanged() or selectionChanged() but I can't do it so far using Python + Qt4, I've tried using cursor.position() and cursor.BlockUnderCursor, QString's functions indexOf() and lastIndexOf() to locate the next and previous "dot" to calculate the paragraph section but always fail. Hope you can help me. Regards. LordFord.
Asked
Active
Viewed 526 times
1 Answers
0
Fragment of text from dot to dot is called sentence, not paragraph. Here's a working example (see the comments):
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()

Pavel Strakhov
- 39,123
- 5
- 88
- 127
-
Great !!! Thx Pavel for your answer, maybe I wasn't clear in my question, but I've seen your code and I'll test it as soon I get to my place, I just wanted to be clear by saying it's possible for the users to select a "region" containing several sentences and then I'd calculate the correct paragraph extension, from dot to dot as in a paragraph, not sentences, understood?. Thx a lot !!! (sorry for my english, isn't my primary language) – Leonel Salazar Videaux Apr 17 '15 at 16:31