I want to indent text of a QPlainTextEdit whan a menu button is pressed. When the button is pressed I ask if there is a selection if not I just indent the current line, if there is I want to indent all the lines in the selection. Right now the code works for the single line, but when indenting a selection is like the last part of the line disappears. For example, if I have the line: "Artificial Intelligence stands no chance against Natural Stupidity.", after the indentation it’s just: " Artificial Intelligence stands no chance against Natural Stupidi and after that if I start writing in that line the text starts to disappear when it reaches what now is the end of the sentence. Also, the program crashes if I click or put the cursor in that line after the part of the sentence that disappear.
The code:
void MainWindow::on_action_Indent_triggered()
{
Document* doc = dynamic_cast<Document*>(ui->tabsManager->currentWidget());
QTextCursor cursor = doc->textArea->textCursor();
cursor.beginEditBlock();
// If ther is no text selected...
if (cursor.selection().isEmpty()) {
cursor.movePosition(QTextCursor::StartOfLine);
cursor.insertText(this->tabLength);
} else { // If the selection is not empty...
cursor.beginEditBlock();
// Save selection start and end
int start = cursor.selectionStart();
int end = cursor.selectionEnd();
cursor.clearSelection();
// Set end to the end of line of the selected line
cursor.setPosition(end);
cursor.movePosition(QTextCursor::EndOfLine);
end = cursor.position();
// Set cursor to the start of the first selected line
cursor.setPosition(start);
cursor.movePosition(QTextCursor::StartOfLine);
start = cursor.position();
// While still in the selection, add " " to the start of each line
do {
cursor.movePosition(QTextCursor::StartOfLine);
cursor.insertText(this->tabLength);
end += this->tabLength.count();
cursor.movePosition(QTextCursor::EndOfLine);
} while (cursor.position() < end && cursor.movePosition(QTextCursor::Down));
// Select the changed areatabLenght
cursor.clearSelection();
cursor.setPosition(start);
while (cursor.position() < end)
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
}
// Set the cursor in the GUI
doc->textArea->setTextCursor(cursor);
cursor.endEditBlock();
}
Document is a Class and textArea is a QTextPlainEdit. this->tabLength is a QString with a value of ” “
The problem is quite simple: you’re calling
beginEditBlock()more times than you callendEditBlock(). Remove thebeginEditBlock()call right after} else {. I could reproduce this problem, and matching[begin|end]EditBlock()calls indeed fixes it.Below is a self-contained example.