How to find a line number after an Enter key press in QTextEdit.
-
wrote on 22 Nov 2021, 10:13 last edited by jenya7
Say I have some lines in QTextEdit.
Line number 1
Line number 2
Line number 3Now I press an Enter key after Line number 2 and it looks like this now
Line number 1
Line number 2
'\r'
Line number 3Now I wont to get a line before the Enter key - Line number 2
So I can do like this
switch (keyEvent->key()) { case Qt::Key_Return: { if (term_str.isEmpty()) { QTextDocument *doc = ui->textEditTerminalTx->document(); QTextBlock tb = doc->findBlockByLineNumber(???); QString s = tb.text(); } } break; }
But how do I get a line number to put in doc->findBlockByLineNumber(???) ?
-
wrote on 22 Nov 2021, 10:50 last edited by mpergand
To retrieve the block under the cursor, you can do:
QTextDocument *doc = ui->textEditTerminalTx->document(); //QTextCursor cursor=doc->textCursor(); QTextCursor cursor=ui->textEditTerminalTx->textCursor(); QTextBlock tb = cursor.block();
-
To retrieve the block under the cursor, you can do:
QTextDocument *doc = ui->textEditTerminalTx->document(); //QTextCursor cursor=doc->textCursor(); QTextCursor cursor=ui->textEditTerminalTx->textCursor(); QTextBlock tb = cursor.block();
wrote on 22 Nov 2021, 10:54 last edited by@mpergand said in How to find a line number after ann Enter key in QTextEdit.:
To retrieve the block under the cursor, you can do:
QTextDocument *doc = ui->textEditTerminalTx->document(); QTextCursor cursor=doc->textCursor(); QTextBlock tb = cursor.block();
I need the line above the cursor - only one line above.
-
wrote on 22 Nov 2021, 10:58 last edited by
int QTextCursor::blockNumber() const
Returns the number of the block the cursor is in, or 0 if the cursor is invalid. -
int QTextCursor::blockNumber() const
Returns the number of the block the cursor is in, or 0 if the cursor is invalid. -
wrote on 22 Nov 2021, 11:06 last edited by
Sorry, it is:
ui->textEditTerminalTx->textCursor(); -
wrote on 22 Nov 2021, 11:18 last edited by VRonin
QTextCursor cursor(ui->textEditTerminalTx->document()); const int oldPosition = cursor.position(); cursor.movePosition(QTextCursor::Up); QString s = cursor.block().text(); cursor.setPosition(oldPosition); //restore the cursor
6/8