Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click default QPushButton when Enter SpinBox

I need to raise the click signal of my QPushButton when I press Enter on QSpinBox (actually on every input box), but even if my button is the default button, the following code doesn't work.

#include <QApplication>
#include <QHBoxLayout>
#include <QPushButton>
#include <QSpinBox>
#include <QMessageBox>

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

  QWidget* window = new QWidget();

  QSpinBox* spinbox = new QSpinBox();
  QPushButton* button = new QPushButton("Ok");
  button->setDefault(true);

  QObject::connect(button, &QPushButton::clicked, []()
  { 
    QMessageBox::question(nullptr, "Test", "Quit?", QMessageBox::Yes|QMessageBox::No);
  });

  QHBoxLayout* layout = new QHBoxLayout();
  layout->addWidget(spinbox);
  layout->addWidget(button);
  window->setLayout(layout);
  window->show();

  return app.exec();
}

How can I fix it?

like image 612
Nick Avatar asked Sep 21 '26 03:09

Nick


1 Answers

You can see in the Qt documentation about QPushButton :

The default button behavior is provided only in dialogs

You are using a QWidget and expect the default button behavior to work. Just use a QDialog instead of QWidget :

QDialog * window = new QDialog();
...
like image 118
Nejat Avatar answered Sep 23 '26 01:09

Nejat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!