Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing last line from QTextEdit

Tags:

c++

qt

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?

like image 580
user1233963 Avatar asked Dec 15 '22 13:12

user1233963


2 Answers

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);
like image 69
masoud Avatar answered Dec 27 '22 10:12

masoud


(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); 
like image 44
Viv Avatar answered Dec 27 '22 11:12

Viv