【发布时间】:2016-09-07 13:10:31
【问题描述】:
我创建了一个类 CalculationManager,它有一个公共槽 process() 发出信号finished()。
void CalculationManager::process()
{
cout << "calc FFT: process()" << endl;
...
emit finished();
}
这与 gui 中的 QThread 一起使用(calculationManager 是一个 QScopedPointer)
void MainWindow::on_pushButtonStartFFT_clicked()
{
cout << "on_pushButtonStartFFT_clicked()" << endl;
...
calculationManager->moveToThread(thread);
connect(thread, SIGNAL (started()), calculationManager.data(), SLOT (process()));
connect(calculationManager.data(), SIGNAL (finished()), thread, SLOT (quit()));
connect(calculationManager.data(), SIGNAL (finished()), this, SLOT (getResultsAndPlot()));
cout << "FFT thread started." << endl;
thread->start();
}
有一个用于地块的槽
void MainWindow::getResultsAndPlot()
{
fftAction doShift = static_cast<fftAction>(calculationManager->shiftBeforeFFT());
updatePlotData(ui->qplot1, calculationManager->data(doShift) );
cout << "update plots" << endl;
}
在 gui 启动时调用该函数。并且输出符合预期:
on_pushButtonStartFFT_clicked()
FFT thread started.
calc FFT: process()
update plots
但是,每次进一步单击按钮都会调用多次,并且更频繁地调用 getResultsAndPlot()。我不知道为什么会这样。我该如何调试或解决这个问题?
on_pushButtonStartFFT_clicked()
FFT thread started.
calc FFT: process()
calc FFT: process()
update plots
update plots
update plots
update plots
on_pushButtonStartFFT_clicked()
FFT thread started.
calc FFT: process()
calc FFT: process()
calc FFT: process()
update plots
update plots
update plots
update plots
update plots
update plots
update plots
update plots
update plots
【问题讨论】:
-
如果你真的想从插槽范围内连接信号和插槽,你需要将
Qt::UniqueConnection传递给connect,例如:connect(thread, SIGNAL (started()), calculationManager.data(), SLOT (process()), Qt::UniqueConnection);
标签: c++ multithreading qt signals-slots