How to get selected text and start and end locations using PySide & QTextEdit?

Question:

I’m able to display a QTextEdit widget and detect when the user changes the selected text. However, I’m unsure how to get the selected text and the integer values that represent the start and end locations of the selection measured as the number of characters from the beginning of the text field. Do I need to create a QTextCursor? I’d appreciate an example. Here is my current code:

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle("My Form")
        self.edit = QTextEdit("Type here...")
        self.button = QPushButton("Show Greetings")
        self.button.clicked.connect(self.greetings)
        self.quit = QPushButton("QUIT")
        self.quit.clicked.connect(app.exit)
        self.edit.selectionChanged.connect(self.handleSelectionChanged)

        layout = QVBoxLayout()
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        layout.addWidget(self.quit)
        self.setLayout(layout)

    def greetings(self):
        print ("Hello %s" % self.edit.text())

    def handleSelectionChanged(self):
        print ("Selection start:%d end%d" % (0,0)) # change to position & anchor

if __name__ == '__main__':
    app = QApplication(sys.argv)
    form=Form()
    form.show()
    sys.exit(app.exec_())
Asked By: davideps

||

Answers:

You can work with selection within QTextEdit via QTextCursor, yes. It has selectionStart and selectionEnd methods which you should use:

def handleSelectionChanged(self):
    cursor = self.edit.textCursor()
    print ("Selection start: %d end: %d" % 
           (cursor.selectionStart(), cursor.selectionEnd()))
Answered By: Dmitry

Here is the start, en and ho to get the text.

        cursor = self.edit.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        self.lbl_status.setText('Selected Count: ' + str(end - start))

        txt = self.edit.textCursor().selectedText()
Answered By: QuentinJS
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.