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?
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();
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With