使用QtConcurrent::run连接单独线程上的信号/插槽
Connecting signals/slots on separate thread using QtConcurrent::run
在我的应用程序中,对话框中有以下代码:
connect(drive, SIGNAL(FileProgressChanged(Progress)), SLOT(OnFileProgressChanged(Progress)));
QtConcurrent::run(this, &ProgressDialog::PerformOperation, Operation, *Path, OutPath, drive);
PerformOperation函数最终调用drive
中的一个函数,该函数会发出信号FileProgressChanged
,而我的OnFileProgressChanged
函数如下:
void ProgressDialog::OnFileProgressChanged(Progress p)
{
if (ui->progressCurrent->maximum() != p.Maximium)
ui->progressCurrent->setMaximum(p.Maximium);
ui->progressCurrent->setValue(p.Current);
if (ui->groupBoxCurrent->title().toStdString() != p.FilePath)
ui->groupBoxCurrent->setTitle(QString::fromStdString(p.FilePath));
}
我读了一些书,发现QFuture和QFutureWatcher支持监控进度值(在这种情况下效果很好!),但它们不能与QtConcurrent::run
一起使用。
如何将在单独线程上发出的移动信号连接到主线程上的插槽,以便监视在发射器线程上调用的函数的进度?
*编辑--*实际上我在代码中发现了一个错误,但它似乎没有影响。我忘了在信号后添加this
作为自变量
connect(drive, SIGNAL(FileProgressChanged(Progress)), this, SLOT(OnFileProgressChanged(Progress)));
尝试将connect()
与QueuedConnection
一起使用,如:
connect(drive, SIGNAL(FileProgressChanged(Progress)), this, SLOT(OnFileProgressChanged(Progress)), Qt::QueuedConnection);
默认情况下,连接应该已经排队(因为发射器和接收器在不同的线程中),但这只会使其更加明确。
编辑:问题是Progress
类型没有在Qt的元对象系统中注册。添加qRegisterMetaType<Progress>("Progress");
解决了问题。
问题似乎不在于跨线程信号/插槽,而在于参数Progress
。这个问题的答案会更详细,但解决方案是通过在声明Progress的头文件中执行以下操作找到的:
struct Progress
{
int Current;
int Maximium;
std::string FilePath;
std::string FolderPath;
int TotalMinimum;
int TotalMaximum;
};
Q_DECLARE_METATYPE(Progress)
在我的形式课上:
qRegisterMetaType<Progress>();
connect(Drive, SIGNAL(FileProgressChanged(const Progress&)), this, SLOT(OnFileProgressChanged(const Progress&)), Qt::QueuedConnection);
很可能不需要将Progress
更改为const Progress&
,但我在测试时留下了它。
相关文章:
- 控制带有信号/插槽的Qt QML滑动视图
- Qt 信号/插槽问题
- Qt moveToThread,带有参数的信号/插槽
- moc 文件中缺少信号插槽
- 文档在哪里说明如果参数不是从末端删除参数,则无法从QT信号插槽连接中删除参数?
- 信号/插槽多线程 Qt
- 通过排队的QT信号插槽连接发送QSHAREDPOINTERS的QVECTOR
- Qimage没有通过信号插槽QT
- 使用 Qt5 的新信号/插槽实现向滑块发出信号
- 一个类中的QT信号/插槽,但从不同的线程发出
- 信号/插槽基类多继承
- 在QT C 中使用QMOVIE和信号/插槽之间在GIF中导航
- 在 for 循环中使用 lambda 函数连接信号插槽
- 不同类别的 2 个对象之间的信号/插槽
- 如何正确使用qt的信号/插槽系统
- Qt信号插槽视觉工作室:似乎未连接
- QACTION信号插槽中的无形UI
- Qt-连接触发动作中的信号/插槽
- Qt 信号插槽类范围类型
- 信号/插槽 Qt5 C++