Why is cursor.clearselection () not working in this example?

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

.

In the constructor, I activate the cursor and set the bool variable for the setFontUnderline method, which is used later.

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

      

The first method below is done by clicking the underline button and the second is by releasing.

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 is first underlined with the push_underlinebutton () method and then instantly de-underlined with the release_underlinebutton method.

With the release_underlinebutton () method, I want to archive that there is no more choice for underline when re-setting setfontunderline (false).

+3


source to share


1 answer


Using a copy of a QTextCursor

The documentation requires a little more reading:

QTextCursor QTextEdit :: textCursor () const

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

He writes that you are getting a copy, so when you try to change the functions of the text cursor, you are working with the copy, not the original.

Hence, you have to make sure that if you want the changes to take effect for the text editing control, you need to set the text cursor like this:

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

      



QTextEdit Direct Cursor

However, there is another way to fix this problem .

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

      

So, you would write something like this:

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

      

+2


source







All Articles