Qt几乎相同的主菜单条目 我使用C++ Qt库,我想做一些事情: connect(actionB11, SIGNAL(triggered()), this, SLOT(SetSomething(1, 1))); connect(actionB12, SIGNAL(triggered()), this, SLOT(SetSomething(1, 2))); connect(actionB21, SIGNAL(triggered()), this, SLOT(SetSomething(2, 1))); connect(actionB22, SIGNAL(triggered()), this, SLOT(SetSomething(2, 2)));
上面的代码不起作用,因为信号函数必须与插槽函数具有相同的数字和参数类型Qt几乎相同的主菜单条目 我使用C++ Qt库,我想做一些事情: connect(actionB11, SIGNAL(triggered()), this, SLOT(SetSomething(1, 1))); connect(actionB12, SIGNAL(triggered()), this, SLOT(SetSomething(1, 2))); connect(actionB21, SIGNAL(triggered()), this, SLOT(SetSomething(2, 1))); connect(actionB22, SIGNAL(triggered()), this, SLOT(SetSomething(2, 2)));,qt,menu,qmenu,Qt,Menu,Qmenu,上面的代码不起作用,因为信号函数必须与插槽函数具有相同的数字和参数类型 有没有办法做到这一点?我不希望有大约20个函数作为SetSomething11,SetSomething12调用SetSomething(1,1)等。您可以修改QAction类 class QMyAction : public QAction { Q_OBJECT QMyAction ( QObject * parent ) : QAction(parent), _x(0), _y(0) {
有没有办法做到这一点?我不希望有大约20个函数作为SetSomething11,SetSomething12调用SetSomething(1,1)等。您可以修改QAction类
class QMyAction : public QAction
{
Q_OBJECT
QMyAction ( QObject * parent ) :
QAction(parent), _x(0), _y(0)
{
connect(this, SIGNAL(triggered(bool)), this, SLOT(re_trigger(bool)));
}
QMyAction ( const QString & text, QObject * parent ) :
QAction (text, parent), _x(0), _y(0)
{
connect(this, SIGNAL(triggered(bool)), this, SLOT(re_trigger(bool)));
}
QMyAction ( const QIcon & icon, const QString & text, QObject * parent ) :
QAction(icon, text, parent), _x(0), _y(0)
{
connect(this, SIGNAL(triggered(bool)), this, SLOT(re_trigger(bool)));
}
void setX(int x)
{
_x = x;
}
int getX()
{
return _x;
}
void setY(int y)
{
_y = y;
}
int getY()
{
return _y;
}
public slots:
void re_trigger(bool)
{
emit triggered(_x, _y);
}
signals:
void triggered(int,int);
private:
int _x;
int _y;
};
现在,您可以将触发器(int,int)连接到SetSomething(int,int)。但是,你必须设置x和y。除非,否则它们将始终为0。在这种情况下,您有三个简单的选项:
QActionGroup::triggered(QAction*)
信号,同时设置每个QAction的数据(请参见QAction::setData()
和QAction::data()
)void Window::onActionGroupTriggered(QAction *action);
{
int i = action->data().toInt();
int a, b;
a = i / 10;
b = i - 10;
setSomething(a, b); // for example if i = 15, then a = 1 and b = 5
}
不能在插槽中使用常量签名,必须在其中使用类型。将信号连接到插槽时,插槽必须具有与信号相同的参数子集,否则无法连接,QObject::connect()将返回false
connect(actionB11, SIGNAL(triggered()),
this, SLOT(SetSomething()));
此插槽不接受任何参数,但可以使用QObject::sender()获取指向发出信号的对象的指针。然后该指针可用于区分信号源:
void SetSomething() {
switch(sender()) {
case actionB11;
// do something
break;
case actionB12;
// do something
break;
case actionB21;
// do something
break;
case actionB22;
// do something
break;
default:
// Exceptional situation
}
}
或者,您可以使用将附加的鉴别参数附加到插槽。非常感谢。QSignalMapper是我正在寻找的,但我希望有人也会使用其他答案。