2

我知道 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。

4

1 回答 1

3

QSignalMapper不是关于从信号向槽发送参数,而是让信号接收者知道“谁”是那个或使用了什么数据。如果您需要知道值和发送者,您可以使用一些内部类映射,或者使用QObject *映射器然后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());
    }
}
于 2013-05-16T07:26:38.377 回答