Autoexclusive property for QPushButtons



  • So I have a bunch of QPushButtons in QGridLayout and they all have autoExclusive = true. These buttons are loaded from a .ui file.
    I added two new QPushButtons to the layout programmatically, and set the same property autoExclusive = true for them.

    In my code when each button is clicked I have the following

      if (!button->isChecked())
       {
          button->setChecked(true);
       }
    

    Now when I click on either of these two new QPushButtons, they don't get unchecked when I click any other button, but the rest of them do, so I'm not sure why the autoexclusive property doesn't work for these buttons that were added programmatically.



  • I haven't been able to find a cleaner solution with respect to the auto exclusive property, but the following works for me in the meantime:

       QGridLayout* gL = QWidget::findChild<QGridLayout *>("buttonsLayout"); 
       QPushButton* btn = 0;
       for(int i = 0; i < gL->count(); ++i)
       {
         if(btn = dynamic_cast<QPushButton*>(gL->itemAt(i)->widget())) 
         {
            if(btn != button) // where button is the button that was just recently clicked.
            {
               btn->setChecked(false);
            }
    
         }
       }
    
    

  • Lifetime Qt Champion

    Hi,

    Are you looking for QButtonGroup::setExclusive ?



  • @SGaist No because my buttons are not part of a QButtonGroup. They are simply arranged in a QGridLayout.


  • Qt Champions 2017

    @Qtstarter121

    Hi.
    autoExclusive only works if they have same parent.
    So check what the working buttons parent is -
    and set the same for the new dynamically allocated buttons.
    If the first buttons are inserted with Designer,
    you can go and see what is set as parent (in setupUI() )
    and use the same.



  • @mrjj Yes the other buttons were created with Qt Designer in a .ui file. I actually looked at the code for the UI and I ensured that my programmatically created buttons had the same parent, but no change. That is why I'm confused as to why this is happening.


  • Qt Champions 2017

    @Qtstarter121
    That is very odd as i did that as a small test.
    Stole the code from setupUI and added via button.clicked() and
    it the worked as the Designer inserted ones.
    I just used a widget with a layout.

    Have you tried a small test ? ( to rule out something else in actual project)


Log in to reply
 

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