QTextEdit - getting selection line numbers

I have the following code (implemented in mouseReleaseEvent) to determine when the user selected lines of text:

QTextCursor cursor = this->textCursor(); int start = cursor.selectionStart(); int end = cursor.selectionEnd(); if(!cursor.hasSelection()) return; // No selection available qWarning() << "start: " << start << " end: " << end << endl; 

problem: I need line numbers where the selection starts and ends. I struggled with blocks and decided nothing, could you give me the key?

+4
source share
2 answers

This may not be the best solution, but it seems to work for me. The selectedLines variable will contain how many rows are selected.

 QTextCursor cursor = ui->plainTextEdit->textCursor(); int selectedLines = 0; //<--- this is it if(!cursor.selection().isEmpty()) { QString str = cursor.selection().toPlainText(); selectedLines = str.count("\n")+1; } 

Hope this will be helpful :)

+4
source

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(); 
0
source

All Articles