title: Qt Program Crashes aftes QTextEdit is modified via QTextCursor
body: <p>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: <code>"Artificial Intelligence stands no chance against Natural Stupidity."</code>, after the indentation it's just: <code>"    Artificial Intelligence stands no chance against Natural Stupidi</code> 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.</p>
  
  <p>The code:</p>
  
  <pre><code>void MainWindow::on_action_Indent_triggered()
  {
      Document* doc = dynamic_cast&lt;Document*&gt;(ui-&gt;tabsManager-&gt;currentWidget());
      QTextCursor cursor = doc-&gt;textArea-&gt;textCursor();
      cursor.beginEditBlock();
  
      // If ther is no text selected...
      if (cursor.selection().isEmpty()) {
          cursor.movePosition(QTextCursor::StartOfLine);
          cursor.insertText(this-&gt;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-&gt;tabLength);
              end += this-&gt;tabLength.count();
              cursor.movePosition(QTextCursor::EndOfLine);
          } while (cursor.position() &lt; end &amp;&amp; cursor.movePosition(QTextCursor::Down));
  
          // Select the changed areatabLenght
          cursor.clearSelection();
          cursor.setPosition(start);
          while (cursor.position() &lt; end)
              cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
      }
      // Set the cursor in the GUI
      doc-&gt;textArea-&gt;setTextCursor(cursor);
      cursor.endEditBlock();
  }
  </code></pre>
  
  <p>Document is a Class and textArea is a QTextPlainEdit. this->tabLength is a QString with a value of "    "</p>