Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the actual visible cursor's line number

I can get the line of the cursor by using QTextEdit.textCursor().blockNumber(), but when one line wrap into multi-lines, it can not return the actual line number.

How can I do that?

like image 471
比尔盖子 Avatar asked Apr 04 '13 14:04

比尔盖子


2 Answers

I wasn't sure it will work, so I wrote a quick test application (Qt 5.0.1) and this works, here is piece of it:

void MainWindow::on_plainTextEdit_cursorPositionChanged()
{
    QPlainTextEdit *edit = qobject_cast<QPlainTextEdit *>(sender());
    Q_ASSERT(edit);
    QTextCursor cursor = edit->textCursor();
    cursor.movePosition(QTextCursor::StartOfLine);

    int lines = 1;
    while(cursor.positionInBlock()>0) {
        cursor.movePosition(QTextCursor::Up);
        lines++;
    }
    QTextBlock block = cursor.block().previous();

    while(block.isValid()) {
        lines += block.lineCount();
        block = block.previous();
    }
    ui->label->setText(QString::number(lines));
}
like image 147
Marek R Avatar answered Nov 15 '22 06:11

Marek R


Here is a similar solution in Python. It fixes the problem I noted in comment on the earlier one above. This is a method in a subclass of QTextEdit:

def getLineAtPosition(self, pos):
  cursor = self.textCursor()
  cursor.setPosition(pos)

  cursor.movePosition(QTextCursor.StartOfLine)
  lines = 0

  lines_text = cursor.block().text().splitlines()
  lines_pos = 0
  for line_text in lines_text:
    lines_pos += len(line_text) + 1
    if lines_pos > cursor.position() - cursor.block().position():
      break
    lines += 1

  block = cursor.block().previous()
  while block.isValid():
    lines += block.lineCount()
    block = block.previous()

  return lines
like image 30
Wingware Avatar answered Nov 15 '22 06:11

Wingware