Click the default QPushButton when Enter SpinBox

I need to raise a click signal QPushButton

when I press Enter on QSpinBox

(actually on every input field), 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 this?

+3


source to share


2 answers


In the Qt documentation, you can see the QPushButton :

The default button behavior is only provided in dialogs



You are using QWidget

and expecting the default button behavior to work. Just use QDialog

instead QWidget

:

QDialog * window = new QDialog();
...

      

+1


source


you can use Event

The function QObject::installEventFilter()

does this by setting up an event filter, whereby the designated filter object receives events for the target in its function QObject::eventFilter()

. an event filter gains the ability to process events before the target is executed, allowing it to check and discard events as needed.

void QObject::installEventFilter ( QObject * filterObj )

      



Sets the event filter filter on this object. For example:

 monitoredObj->installEventFilter(filterObj);

      

An event filter is an object that receives all events that are dispatched to that object. The filter can either stop the event or forward it to this object. An event filter filter accepts events through its eventFilter (). The eventFilter () function must return true if the event is to be filtered (i.e. stopped); otherwise it must return false.

0


source







All Articles