Important: Please read the Qt Code of Conduct -

How do I find the first and (more important) the last QTextBlock in a selection provided by QTextCursor?

  • I have a QTextEdit, and in it I want to determine the first and last selected block in the selection associated with the cursor returned by QTextEdit::textCursor().

    So far I don't see anything in the API that lets me do this.


  • @
    QTextCursor cursor = textEdit->textCursor();
    qDebug() << "your selection : " << cursor.selectionStart() << "~" << cursor.selectionEnd();

    Hope this helps.

  • Thanks for the reply. -Unfortunately I'm not sure that helps what I'm aiming. Sorry for not going into depth about the reason earlier.-

    I'm actually trying to get the QTextBlock. The reason is for bulleted list management. I want to determine the text blocks that are covered by the user's selection. So if they have parts of a bulleted lists selected (could be across different levels of indentation) I can increment/decrement the indentation of each selected block without affecting the non-selected portions of the list.

    Your suggestion worked for me. Using the selectionStart() and selectionEnd() methods you pointed out along with QTextDocument::findBlock(pos) I got what I needed.

    QTextCursor c = textCursor();
    QTextBlock b1 = document()->findBlock(c.selectionStart());
    QTextBlock b2 = document()->findBlock(c.selectionEnd());

Log in to reply