QTextEdit - get selection line numbers
Asked Answered
W

2

5

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?

Waikiki answered 26/7, 2012 at 20:1 Comment(0)
H
6

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 :)

Hyaloplasm answered 28/7, 2012 at 13:6 Comment(0)
T
1

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();
Turgescent answered 26/7, 2012 at 20:57 Comment(1)
There's a problem: I knew how to do this before you posted, but I'm trying to get LINE numbers, not block numbers. Block != lines, and in my document there are two-lines blocks, so I can't use your codeWaikiki

© 2022 - 2024 — McMap. All rights reserved.