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?
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));
}
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
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