Search code examples
c++qtqtguiqtexteditqtextcursor

Why does cursor.clearselection() does not work in this example?


I am trying to create a button which underlines the selected text of my QTextEdit instance.

In the constructor, I am activating the cursor and setting a bool variable for the setFontUnderline method used later.

QTextCursor cursor1 = ui.myQTextfield->textCursor();
ui.myQTextfield->ensureCursorVisible();
test1 = false;

The first method below is executed by pressing the underline button and the second by releasing that.

void Hauptfenster::pressed_underlinebutton()
{
    test1 = true;
    ui.myQTextfield->setFontUnderline(test1);   
}

void Hauptfenster::released_underlinebutton()
{
    cursor.clearSelection();
    test1 = false;
    ui.myQTextfield->setFontUnderline(test1);
}

The problem is that with this code, the selected text first gets underlined by the pressed_underlinebutton() method and then instantly gets de-underlined with the released_underlinebutton method.

With the released_underlinebutton() method, I want to archieve that there is no more selection to de-underline while setting setfontunderline(false) again.


Solution

  • Using a QTextCursor copy

    The documentation needs a bit more reading:

    QTextCursor QTextEdit::​textCursor() const

    Returns a copy of the QTextCursor that represents the currently visible cursor. Note that changes on the returned cursor do not affect QTextEdit's cursor; use setTextCursor() to update the visible cursor.

    It writes that you get a copy, so when you try to change the text cursor features, you are operating on the copy rather than the original.

    Therefore, you ought to make sure that if you want the changes to take effect on the text edit control, you need to set the text cursor back as follows:

    cursor.clearSelection();
    ui.myQTextfield->setTextCursor(cursor); // \o/
    

    Move the cursor of QTextEdit directly

    There is another way to solve this issue, however.

    QTextCursor::Left   9   Move left one character.
    QTextCursor::End    11  Move to the end of the document.
    

    So, you would be writing something like this:

    ui.myQTextfield->moveCursor(QTextCursor::End)
    ui.myQTextfield->moveCursor(QTextCursor::Left)