Problem while moving QTextCursor



  • i have an action called bold, when i select text then run this action this code will run:
    @
    void MarkEditWindow::on_actionBold_triggered()
    {
    QTextCursor selectionBegin(ui->markdownEdit->document());
    selectionBegin.setPosition(ui->markdownEdit->textCursor().anchor());
    selectionBegin.insertText("**");

    QTextCursor selectionEnd(ui->markdownEdit->document());
    selectionEnd.setPosition(ui->markdownEdit->textCursor().position());
    selectionEnd.insertText("**");
    

    }
    @

    now for example i wrote "test" then run the action the result is "test" and the selected text will be "test**" (missing first '**')
    how can i move the cursor after selection to make it select "test" or even select "test" only
    i tried a lot of things and didn't work, like:
    @
    selectionEnd.movePosition(QTextCursor::Left);
    selectionEnd.movePosition(QTextCursor::Left);
    @
    but didn't work! :-(


  • Lifetime Qt Champion

    Hi,

    Are you thinking of something like

    @
    QTextCursor cursor = _textEdit->textCursor();
    int start = cursor.selectionStart();
    int end = cursor.selectionEnd();
    cursor.setPosition(start);
    cursor.insertText("");
    cursor.setPosition(end+2);
    cursor.insertText("
    ");
    @

    ?



  • yeah, but:
    @
    cursor.setPosition(end-2);
    @
    how to do that?


  • Lifetime Qt Champion

    @
    // Go back to start and redo the selection
    cursor.setPosition(start + 2);
    cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, (end - start));
    _textEdit->setTextCursor(cursor);
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.