首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用QtConcurrent::run在单独线程上连接信号/插槽

使用QtConcurrent::run在单独线程上连接信号/插槽
EN

Stack Overflow用户
提问于 2012-02-20 19:57:34
回答 2查看 5.7K关注 0票数 3

在我的应用程序中,对话框中有以下代码:

代码语言:javascript
运行
复制
connect(drive, SIGNAL(FileProgressChanged(Progress)), SLOT(OnFileProgressChanged(Progress)));

QtConcurrent::run(this, &ProgressDialog::PerformOperation, Operation, *Path, OutPath, drive);

PerformOperation函数最终调用drive中的一个函数,该函数发出信号FileProgressChanged,我的OnFileProgressChanged函数如下所示:

代码语言:javascript
运行
复制
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));
}

我正在进行一些阅读,并看到QFutureQFutureWatcher支持监视进度值(在这种情况下会很好!),但是这些值不能与QtConcurrent::run一起使用。

如何将在独立线程上被移动的信号连接到主线程上的插槽,以便监视在发射器线程上调用的函数的进度?

*编辑我忘了在信号之后添加this作为参数

代码语言:javascript
运行
复制
connect(drive, SIGNAL(FileProgressChanged(Progress)), this, SLOT(OnFileProgressChanged(Progress)));
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-21 00:47:25

尝试将connect()QueuedConnection结合使用,例如:

代码语言:javascript
运行
复制
connect(drive, SIGNAL(FileProgressChanged(Progress)), this, SLOT(OnFileProgressChanged(Progress)), Qt::QueuedConnection);

默认情况下,连接应该已经排队(因为发射器和接收器位于不同的线程中),但这只会使它更加显式。

编辑:问题是Progress类型没有注册到Qt的元对象系统中。添加qRegisterMetaType<Progress>("Progress");解决了这个问题。

票数 1
EN

Stack Overflow用户

发布于 2012-02-21 01:00:22

看起来问题不在于跨线程信号/时隙,而在于参数Progress问题的回答更详细,但是通过在声明进度的头文件中执行以下操作找到了解决方案:

代码语言:javascript
运行
复制
struct Progress
{
    int Current;
    int Maximium;
    std::string FilePath;
    std::string FolderPath;
    int TotalMinimum;
    int TotalMaximum;
};

Q_DECLARE_METATYPE(Progress)

在我的形式课上:

代码语言:javascript
运行
复制
qRegisterMetaType<Progress>();
    connect(Drive, SIGNAL(FileProgressChanged(const Progress&)), this, SLOT(OnFileProgressChanged(const Progress&)), Qt::QueuedConnection);

很可能不需要将Progress更改为const Progress&,但我在测试时离开了它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9367582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档