我知道QSignalMapper适合这样的条件:
QSignalMapper *signalMapper = new QSignalMapper(this);
connect(signalMapper, SIGNAL(mapped(int)), this, SIGNAL(SetSlice(int)));
connect(this->ui->button_1, SIGNAL(slicked()), signalMapper, SLOT(map()));
connect(this->ui->button_2, SIGNAL(clicked()), signalMapper, SLOT(map()));
connect(this->ui->button_3, SIGNAL(clicked()), signalMapper, SLOT(map()));
现在我想要实现3个滑块,所有滑块都有一个SLOT按钮:
QSignalMapper *signalMapper = new QSignalMapper(this);
connect(signalMapper, SIGNAL(mapped(int)), this, SIGNAL(SetSlice(int)));
connect(this->ui->verticalSlider_1, SIGNAL(valueChanged(int)), signalMapper, SLOT(map()));
connect(this->ui->verticalSlider_2, SIGNAL(valueChanged(int)), signalMapper, SLOT(map()));
connect(this->ui->verticalSlider_3, SIGNAL(valueChanged(int)), signalMapper, SLOT(map()));
正如您所看到的,这与SIGNAL和SLOT之间的一致规则相矛盾。 这里有解决方法吗?我正在使用Qt4。
答案 0 :(得分:3)
QSignalMapper
不是要将信号从信号发送到插槽,而是让信号接收器知道“谁”是那个或者使用什么数据。如果你需要知道值和发送者,你可以使用一些内部类映射,或使用QObject *
mapper然后将QObject *
转换为滑块。
QSignalMapper * mapper = new QSignalMapper(this);
connect(mapper, SIGNAL(map(QWidget *)), this, SLOT(SetSlice(QWidget *)));
mapper->setMapping(this->ui->verticalSlider_1, this->ui->verticalSlider_1);
mapper->setMapping(this->ui->verticalSlider_2, this->ui->verticalSlider_2);
mapper->setMapping(this->ui->verticalSlider_3, this->ui->verticalSlider_3);
这是插槽体:
void YourClass::SetSlice(QWidget *wgt)
{
QSlider * slider = qobject_cast<QSlider *>(wgt);
if(slider) {
SetSlice(slider->value());
}
}