'How to define where to move focus when focused widget gets disabled?

I have buttons "A", "B", "C" and a list view in a dialog. The enabled/disabled state of the buttons depends on the data and current index in the list view. The buttons get enabled or disabled independently of each other, so for example button "A" can be enabled while button "B" is disabled.

Any of these buttons can have keyboard focus (if it is enabled). But when it gets disabled, I want the focus to be moved to the list view (as the central widget in the dialog). But what actually happens is that the focus moves to the next button which is enabled.

For example when focused button "A" gets disabled by some change in the data and button "B" is still enabled, then the focus moves to button "B". But I actually want it to move to the list view instead of the button "B".

I want the focus of these buttons to be activated by mouse and tab key, so I cannot use setFocusPolicy(Qt::NoFocus).

This is the slot which updates the button states. It is connected to various signals from the view, its model and multiple other widgets.

void Dialog::updateButtonStates()
{
    int index = m_listView->currentIndex().row();
    int count = m_listView->model()->rowCount();
    m_aButton->setEnabled(index > 0);
    m_bButton->setEnabled(index >= 0 && index < count - 1);
    m_cButton->setEnabled(count > 0);
}

What is the simplest code to achieve the desired behavior?

Note: this is of course a simplified example, in my real case I have many more buttons present in the dialog and I would like to solve this in a simple why so that I do not need to check individually each button whether it had focus and whether its got disabled or not...



Solution 1:[1]

I think I have found the correct solution a few moments after posting my question. It is actually quite simple.

void Dialog::updateButtonStates()
{
    QWidget *w = focusWidget(); // remember who has the focus in the dialog now
    
    int index = m_listView->currentIndex().row();
    int count = m_listView->model()->rowCount();
    m_aButton->setEnabled(index > 0);
    m_bButton->setEnabled(index >= 0 && index < count - 1);
    m_cButton->setEnabled(count > 0);
   
    if (w != focusWidget()) // has the focus changed after disabling buttons?
    {
        m_listView->setFocus();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HiFile the best file manager