把一个参数传给一个槽

我想用一堆QActions和QMenus来重写mouseReleaseEvent …

connect(action1, SIGNAL(triggered()), this, SLOT(onStepIncreased())); connect(action5, SIGNAL(triggered()), this, SLOT(onStepIncreased())); connect(action10, SIGNAL(triggered()), this, SLOT(onStepIncreased())); connect(action25, SIGNAL(triggered()), this, SLOT(onStepIncreased())); connect(action50, SIGNAL(triggered()), this, SLOT(onStepIncreased())); 

所以我想传递一个参数到onStepIncreased (你可以想象它们是1,5,10,25,50)。 你知道我该怎么做吗?

使用QSignalMapper 。 喜欢这个:

 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(onStepIncreased(int))) ; 

使用Qt 5和C ++ 11编译器,做这种事情的惯用方法是给一个仿函数来connect

 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); }); 

connect的第三个参数名义上是可选的。 它用来设置函数将执行的线程上下文。 当函子使用QObject实例时,总是有必要的。 如果函子使用多个QObject实例,它们应该有一些共同的父项来pipe理它们的生命周期,并且函数应该引用那个父对象,或者应该确保这些对象将会比函数更加有效。

在Windows上,这适用于MSVC2012及更新版本。

QObject::sender()函数返回一个指向已经通知槽的对象的指针。 你可以用这个来找出哪个动作被触发了

也许你可以用一个m_increase成员variables来inheritanceQAction。
将triggered()信号连接到新QAction子类的一个插槽,并发出一个新的信号(例如触发的(int数)),并带有正确的参数。
例如

 class MyAction:public QAction { public: MyAction(int increase, ...) :QAction(...), m_increase(increase) { connect(this, SIGNAL(triggered()), this, SLOT(onTriggered())); } protected Q_SLOTS: void onTriggered() { emit triggered(m_increase); } Q_SIGNALS: void triggered(int increase); private: int m_increase; };