C++ 输入SpinBox时,单击默认QPushButton

C++ 输入SpinBox时,单击默认QPushButton,c++,qt,button,click,default,C++,Qt,Button,Click,Default,当我在QSpinBox上按Enter键时,我需要发出我的QPushButton的点击信号(实际上在每个输入框上),但即使我的按钮是默认按钮,以下代码也不起作用 #include <QApplication> #include <QHBoxLayout> #include <QPushButton> #include <QSpinBox> #include <QMessageBox> int main(int argc, char* a

当我在
QSpinBox
上按Enter键时,我需要发出我的
QPushButton
的点击信号(实际上在每个输入框上),但即使我的按钮是默认按钮,以下代码也不起作用

#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();
}
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[])
{
QApplication应用程序(argc、argv);
QWidget*窗口=新的QWidget();
QSpinBox*spinbox=新QSpinBox();
QPushButton*按钮=新的QPushButton(“确定”);
按钮->设置默认值(真);
QObject::connect(按钮,&QPushButton::单击,[]()
{ 
QMessageBox::问题(nullptr,“测试”,“退出?”,QMessageBox::是| QMessageBox::否);
});
QHBoxLayout*布局=新的QHBoxLayout();
布局->添加小部件(spinbox);
布局->添加小部件(按钮);
窗口->设置布局(布局);
窗口->显示();
返回app.exec();
}

如何修复它?

您可以在Qt文档中看到关于:

默认按钮行为仅在对话框中提供

您正在使用
QWidget
,并期望默认按钮行为正常工作。只需使用
QDialog
而不是
QWidget

QDialog * window = new QDialog();
...
你可以用

QObject::installEventFilter()
函数通过设置 事件筛选器,使指定的筛选器对象接收 目标对象在其
QObject::eventFilter()函数中的事件。一
事件筛选器在目标对象之前处理事件,
允许它根据需要检查和丢弃事件

在此对象上安装事件筛选器filterObj。例如:

 monitoredObj->installEventFilter(filterObj);
事件筛选器是接收发送到的所有事件的对象 这个物体。筛选器可以停止事件或将其转发到 这个物体。事件筛选器filterObj通过其 eventFilter()函数。如果发生以下情况,则eventFilter()函数必须返回true 应过滤事件(即停止);否则它必须返回 错

 monitoredObj->installEventFilter(filterObj);