I'm using this bit of code to try to remove the last line from a QTextEdit:
ui->textEdit_2->textCursor().setPosition( QTextCursor::End);
auto k = ui->textEdit_2->textCursor().currentTable();
k->removeRows(k->rows() - 1, 1);
but I get a segmentation fault. After debugging I found that that k is null when removeRows is called.
Am I doing something wrong? if yes, how can it be fixed?
Try this (Tested):
ui->textEdit_2->setFocus();
QTextCursor storeCursorPos = ui->textEdit_2->textCursor();
ui->textEdit_2->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
ui->textEdit_2->moveCursor(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
ui->textEdit_2->moveCursor(QTextCursor::End, QTextCursor::KeepAnchor);
ui->textEdit_2->textCursor().removeSelectedText();
ui->textEdit_2->textCursor().deletePreviousChar();
ui->textEdit_2->setTextCursor(storeCursorPos);
(Just leaving this undeleted to show another way of doing the same action)
You can try this to remove last line:
QTextCursor cursor = ui->textEdit_2->textCursor();
cursor.movePosition(QTextCursor::End);
cursor.select(QTextCursor::LineUnderCursor);
cursor.removeSelectedText();
cursor.deletePreviousChar(); // Added to trim the newline char when removing last line
ui->textEdit_2->setTextCursor(cursor);
If you want to restore cursor position to where it originally was, Just save the cursor position before calling
cursor.movePosition(QTextCursor::End);
and then after removing text.
ui->textEdit_2->setTextCursor(savedCursorPos);
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