Qt使用connect函数时向slot传递参数

版权声明:转载请注明来源: https://blog.csdn.net/imred/article/details/72940365

设想这样一种场景:共有5个button,button1~button5,点击button1时输出“button 1 clicked”,点击button2时输出“button 2 clicked”,该如何实现呢?
最粗暴的实现是写5个slot,然后将button与slot分别connect,但这明显会增加许多重复代码,不是一种好的实现。
一种比较好的方式是使用QSignalMapper,它可以接收无参数的signal,然后重新发射出有参数的signal,这些参数的类型可以是int、QString、QWidget *或QObject *:

QSignalMapper *signalMapper = new QSignalMapper(this);

connect(button1, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(button2, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(button3, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(button4, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(button5, SIGNAL(triggered()), signalMapper, SLOT(map()));

signalMapper->setMapping(button1, 1);
signalMapper->setMapping(button2, 2);
signalMapper->setMapping(button3, 3);
signalMapper->setMapping(button4, 4);
signalMapper->setMapping(button5, 5);

connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(printMsg(int)));

然后在printMsg(int)中根据不同的输入参数输出信息即可。
可参考https://stackoverflow.com/questions/5153157/passing-an-argument-to-a-slot


转发请注明来源http://blog.csdn.net/imred

没有更多推荐了,返回首页