3

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?

2 Answers 2

1

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();
...
Sign up to request clarification or add additional context in comments.

Comments

0

you can use Event

The QObject::installEventFilter() function enables this by setting up an event filter, causing a nominated filter object to receive the events for a target object in its QObject::eventFilter() function. An event filter gets to process events before the target object does, allowing it to inspect and discard the events as required.

void QObject::installEventFilter ( QObject * filterObj )

Installs an event filter filterObj on this object. For example:

 monitoredObj->installEventFilter(filterObj);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.