Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Can't set selection on QLabel after changing its text
Qt 6.11 is out! See what's new in the release blog

Can't set selection on QLabel after changing its text

Scheduled Pinned Locked Moved General and Desktop
qlabel
2 Posts 1 Posters 1.9k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    AlaaM
    wrote on last edited by AlaaM
    #1

    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:
    label->setText("");
    for(int i=0; i<ABC; i++){
       label->setText(label->text() + ('a' + i));
    }
    
    • Now set selection:
    highlightNextChar(label);
    
    void MyClass::highlightNextChar(QLabel* label)
    {
        int selectionEnd = label->selectionStart();
        if(selectionEnd == label->text().length()-1){
            return;
        }
        label->setSelection(selectionEnd+1,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->setFocus();
    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?

    1 Reply Last reply
    0
    • A Offline
      A Offline
      AlaaM
      wrote on last edited by AlaaM
      #2

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

      label->setFocus();
      label->setSelection(INDEX , 1);
      

      to:

      label->clearFocus();
      label->setFocus();
      label->setSelection(INDEX , 1);
      

      That's very weird.

      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved