Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTextEdit - get selection line numbers

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?

like image 672
Johnny Pauling Avatar asked Jul 26 '12 20:07

Johnny Pauling


2 Answers

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

like image 172
Balázs Édes Avatar answered Oct 24 '22 13:10

Balázs Édes


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();
like image 45
Torsten Avatar answered Oct 24 '22 11:10

Torsten