I have the following code (implemented in the mouseReleaseEvent) to detect when the user has 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;
the problem is: I need the line numbers where the selection begins and ends. I've been struggling with blocks and solved nothing, can you please give me a clue?
It is possible, that it isn't the best solution, but it seems to work for me. The variable selectedLines
will contain, how many lines 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;
}
I hope, that it will be helpful :)
I see easy way to use chain of 2 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 position to begin of selection. Get current block, get layout of block and use Qt API for getting line number. I doesn't know which line number returned is absolute for whole document or for layout. If only for layout, you need some additional process for calculate line numbers for previous blocks.
for (QTextBlock block = cursor.block(). previous(); block.isValid(); block = block.previous())
lines += block.lineCount();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With