Can you think of a better code to uncheck an action of a QActionGroup?



  • So i have a qactiongroup on my QSystemTrayIcon, and every action on it is checkable
    So it kinda works like the widget radiobutton

    the difference is that when you reclick one checked action i want it to be unchecked..
    The only way i tought to accomplish this is :

    @if(!action1->isChecked())
    {
    action1->setCheckable(true);
    action1->setChecked(true);
    }
    else
    action1->setCheckable(false);@

    Simply because clicking on the action always makes it checked...
    U got any better ideas?


  • Lifetime Qt Champion

    Hi,

    I'm not sure to understand you right, you wan't an exclusive QActionGroup that is not really exclusive ?


  • Moderators

    It's a bit old topic but I recently had a similar need. An editor that has a three actions: translate, rotate and scale. I needed a way to check exactly one or none of these, i.e. if the current action was clicked it should be unchecked.

    The way I did it was this:
    @
    void makeGroupOptional(QActionGroup* group)
    {
    group->connect(group, &QActionGroup::triggered, [](QAction* action) {
    static QAction* lastAction = nullptr;
    if(action == lastAction) {
    action->setChecked(false);
    lastAction = nullptr;
    }
    else
    lastAction = action;
    });
    }
    @
    The nice thing about it is that it's a sort of "fire and forget" function ie. you don't have to worry about the actual contents of the group. You can add, modify and remove actions from the group without ever modifying this piece.


Log in to reply
 

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