我正在尝试将按钮连接到函数,因此当我按下按钮时,将使用特定参数调用该函数.我有
class FieldGridWidget : public QWidget
{
Q_OBJECT
public:
FieldGridWidget(QWidget *parent=0);
~FieldGridWidget();
public slots:
void resizeGrid(int n);
private:
QGridLayout* _gridLayout;
QVector<QPushButton*> _buttonGrid;
};
Run Code Online (Sandbox Code Playgroud)
然后按钮
_button3 = new QPushButton("3x3", this);
Run Code Online (Sandbox Code Playgroud)
并且我正在尝试连接它,所以如果单击,则resizeGrid使用参数3调用该函数.为此,我正在尝试
connect(_button3, SIGNAL(clicked()), _fieldGrid, SLOT(resizeGrid(3))); //this is line 21
Run Code Online (Sandbox Code Playgroud)
但是我得到了运行时错误
QObject::connect: No such slot FieldGridWidget::resizeGrid(3) in ../filename.cpp:21
我究竟做错了什么?或者,如果我按下按钮,我怎么能这样做呢resizeGrid(3)?谢谢!
您无法直接将值传递给Qt中的插槽,如SLOT(resizeGrid(3)).参数SLOT应该只是方法(resizeGrid())的签名.
有两种方法可以为插槽添加参数.关于如何将参数传递给插槽的这个问题显示了一些解决方案,在此重复.(去投票吧!)
而不是连接插槽,连接到仿函数,如Kuba Ober在这个答案中所描述的那样:
connect(action1, &QAction::triggered, this, [this]{ onStepIncreased(1); });
connect(action5, &QAction::triggered, this, [this]{ onStepIncreased(5); });
connect(action10, &QAction::triggered, this, [this]{ onStepIncreased(10); });
connect(action25, &QAction::triggered, this, [this]{ onStepIncreased(25); });
connect(action50, &QAction::triggered, this, [this]{ onStepIncreased(50); });
Run Code Online (Sandbox Code Playgroud)
您可以使用a QSignalMapper来执行您想要的操作,如TonyK在此答案中所述:
QSignalMapper* signalMapper = new QSignalMapper (this) ;
connect (action1, SIGNAL(triggered()), signalMapper, SLOT(map())) ;
connect (action5, SIGNAL(triggered()), signalMapper, SLOT(map())) ;
connect (action10, SIGNAL(triggered()), signalMapper, SLOT(map())) ;
connect (action25, SIGNAL(triggered()), signalMapper, SLOT(map())) ;
connect (action50, SIGNAL(triggered()), signalMapper, SLOT(map())) ;
signalMapper -> setMapping (action1, 1) ;
signalMapper -> setMapping (action5, 5) ;
signalMapper -> setMapping (action10, 10) ;
signalMapper -> setMapping (action25, 25) ;
signalMapper -> setMapping (action50, 50) ;
connect (signalMapper, SIGNAL(mapped(int)), this, SLOT(resizeGrid(int))) ;
Run Code Online (Sandbox Code Playgroud)