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

C++ 使用QtConcurrent::run在单独的线程上连接信号/插槽,c++,multithreading,qt,qtconcurrent,C++,Multithreading,Qt,Qtconcurrent,在我的应用程序中,对话框中有以下代码: connect(drive, SIGNAL(FileProgressChanged(Progress)), SLOT(OnFileProgressChanged(Progress))); QtConcurrent::run(this, &ProgressDialog::PerformOperation, Operation, *Path, OutPath, drive); PerformOperation函数最终调用驱动器中的一个函数,该函数发

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

connect(drive, SIGNAL(FileProgressChanged(Progress)), SLOT(OnFileProgressChanged(Progress)));

QtConcurrent::run(this, &ProgressDialog::PerformOperation, Operation, *Path, OutPath, drive);
PerformOperation函数最终调用
驱动器中的一个函数,该函数发出信号
FileProgressChanged
,my
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));
}
我读了一些书,看到了这一点,并支持监视进度值(在这种情况下非常有用!),但这些值不能与
QtConcurrent::run
结合使用

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

*编辑--*我实际上发现我的代码有一个错误,但似乎没有影响。我忘了在信号后面添加
这个
作为参数

connect(drive, SIGNAL(FileProgressChanged(Progress)), this, SLOT(OnFileProgressChanged(Progress)));
尝试将
connect()
QueuedConnection
一起使用,如:

connect(drive, SIGNAL(FileProgressChanged(Progress)), this, SLOT(OnFileProgressChanged(Progress)), Qt::QueuedConnection);
默认情况下,连接应该已经排队(因为发射器和接收器在不同的线程中),但这只会使它更显式


编辑:问题是
进度
类型未注册到Qt的元对象系统。添加
qRegisterMetaType(“进度”)修复了该问题。

似乎问题不在于交叉线程信号/插槽,而在于参数
进度
。问题的答案更为详细,但解决方案是通过在声明进度的头文件中执行以下操作找到的:

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);
qRegisterMetaType();
连接(驱动器、信号(FileProgressChanged(const Progress&))、此、插槽(OnFileProgressChanged(const Progress&))、Qt::QueuedConnection;

Progress
更改为
const Progress&
很可能是不需要的,但我在测试时留下了它。

我真的不明白,乍一看这似乎应该是可行的。线程从
drive
发出
FileProgressChanged
——是否正确调用
OnFileProgressChanged
?从一个线程向另一个线程的插槽发出信号应该可以正常工作(它会排队)。在发出信号的函数上,代码是
emit FileProgressChanged(p)
。如果我这样做,它会把我带到,但我在OnFileProgressChanged的断点从未命中。没有骰子。我做了更多的搜索,我相信答案就在这里。信号/插槽连接在没有参数的情况下工作正常。这也是可能的。您需要有一个
qRegisterMetaType(“Progress”)行在调用
connect()
之前的某个位置。如果不考虑这一点,应该会抛出一个错误(无论是在编译时还是在运行时)!谢天谢地,这是一个很简单的解决办法。谢谢你的帮助。很高兴听到。我很惊讶它在运行时没有抛出错误,但是,您是否在观察输出(如QtCreator的“应用程序输出”窗格)?另外,请注意将此标记为可接受的答案:)我想说我会把这个标记为答案,所以。。。对我不想等两天。我的应用程序吐出了太多的信息,以至于无法注意到输出中的任何内容,因此如果它吐出了,那么它就不会被注意到。