Important: Please read the Qt Code of Conduct -

Can't set selection on QLabel after changing its text

  • Every time I use .setText() on a QLabel it loses the previous selection. And then if I re-set the selection, it doesn't show any selection.

    Here's my code:

    • First, initialize QLabel with text, in class constructor:
    for(int i=0; i<ABC; i++){
       label->setText(label->text() + ('a' + i));
    • Now set selection:
    void MyClass::highlightNextChar(QLabel* label)
        int selectionEnd = label->selectionStart();
        if(selectionEnd == label->text().length()-1){

    I do this as I click the RIGHT_BUTTON on the keyboard, highlighting the next char on every hit.
    All of this works.
    At some point I change the text on the label:

    label->setText(label->text() + label->text().mid(0,1)); //add char
    label->setText(label->text().mid(1)); //shift left

    At this point, the selection disappears. I set focus on the label and then try to set selection:

    label->setSelection(INDEX , 1);

    The focus is set but setSelection() isn't working. It simply does nothing.
    I also tried executing the last 2 commands after a 3-second timer finishes. Also then setSelection does nothing.

    Any help?

  • I solved it.
    Before setting selection, do clearFocus() and only then setFocus().
    So, change these 2 lines:

    label->setSelection(INDEX , 1);


    label->setSelection(INDEX , 1);

    That's very weird.

Log in to reply