I see an easy way to use a chain of two QTextCursor methods - setPosition and blockNumber.
QTextCursor cursor = this->textCursor(); int start = cursor.selectionStart(); int end = cursor.selectionEnd(); if(!cursor.hasSelection()) return; // No selection available cursor.setPosition(start); int firstLine = cursor.blockNumber(); cursor.setPosition(end, QTextCursor::KeepAnchor); int lastLine = cursor.blockNumber(); qWarning() << "start: " << firstLine << " end: " << lastLine << endl;
UPD:
cursor.setPosition(start); cursor.block().layout()->lineForTextPosition(start).lineNumber(); // or cursor.block().layout()->lineAt(<relative pos from start of block>).lineNumber();
Set the position to start the selection. Get the current block, get the block layout and use the Qt API to get the line number. I do not know which line number was returned absolute for the entire document or for the layout. If only for layout, you need an additional process to calculate line numbers for previous blocks.
for (QTextBlock block = cursor.block(). previous(); block.isValid(); block = block.previous()) lines += block.lineCount();
source share