QButtonBox set default button

In Qt 5.3, the default button for the QButtonBox is Cancel, and I want to set it to Ok, but I cannot find a way to achieve it. I tried this:

QPushButton * b = ui->buttonBox->button(QDialogButtonBox::Ok);
b->setDefault(true);

but without success, he throws:

/Users/thomas/Dev/Joker/app/Joker/RulerSpaceDialog.cpp:18:3: error: member access into incomplete type 'QPushButton'
        b->setDefault(true);
         ^
/Applications/Qt/5.3/clang_64/lib/QtWidgets.framework/Versions/5/Headers/qdialog.h:50:7: note: forward declaration of 'QPushButton'
class QPushButton;
      ^
1 error generated.

I am also trying to browse through a list but no luck ....

EDIT:

I added include to get this code:

QPushButton * b = ui->buttonBox->button(QDialogButtonBox::Ok);
if(b)
{
    b->setDefault(true);
    qDebug() << b->text();
}

Which outputs Okwait 2 seconds, then highlight the button Cancel...

+4
source share
1 answer

Make sure you set auto default false , use setAutoDefault(false)as well setDefault(false).

Sample code below.

#include <QtWidgets>

int main(int argc, char** argv)
{
  QApplication app(argc, argv);

  QDialogButtonBox* bb = new QDialogButtonBox(
    QDialogButtonBox::Ok | QDialogButtonBox::Cancel);

  QPushButton* okBtn = bb->button(QDialogButtonBox::Ok);
  okBtn->setAutoDefault(true);
  okBtn->setDefault(true);

  QPushButton* caBtn = bb->button(QDialogButtonBox::Cancel);
  caBtn->setAutoDefault(false);
  caBtn->setDefault(false);

  QDialog dlg;
  QVBoxLayout* dlgLayout = new QVBoxLayout();
  dlgLayout->addWidget(bb);
  dlg.setLayout(dlgLayout);
  dlg.show();
  return app.exec();
}

Windows, "" , , setAutoDefault setDefault.

+3

Source: https://habr.com/ru/post/1547029/


All Articles