QThread 退出崩溃中的 QProgressBar 更新

QProgressBar update in QThread quitting crashes

我有以下代码可以按预期工作。它更新每个 for 循环中的进度条值。我遇到的唯一问题是当我完成并在方法 OnProcessUserRowsStarted 中调用 emit ProcessUserRowsFinished() 时程序崩溃。

class UsersProcess: public QObject
{
    Q_OBJECT

public:
    UsersProcess(CTCore::DBConnect* db_context, UserSettingsMap user_settings_map);
    void SetProgressBar(QProgressBar *progress_bar);

private:

    QProgressBar *progressBar;
    QSharedPointer<QList<CTCoreZen::User>> listUsers;
    QScopedPointer<QThread> threadRowWorker;

signals:
    void ProcessUserRowsFinished();
    void ProgressBarSetValue(int value);

}   

void UsersProcess::SetProgressBar(QProgressBar *progress_bar)
{
    this->progressBar = progress_bar;
}

void UsersProcess::OnUserListSuccess(QList<CTCoreZen::User> *users)
{
    this->listUsers.reset(users);

    this->progressBar->setVisible(true);
    this->progressBar->setTextVisible(true);
    this->progressBar->setMinimum(0);
    this->progressBar->setMaximum(this->listUsers->size());
    this->progressBar->setValue(0);



    this->threadRowWorker.reset(new QThread());
    this->moveToThread(this->threadRowWorker.data());

    connect(this->threadRowWorker.data(), &QThread::started, this, &UsersProcess::OnProcessUserRowsStarted);

    connect(this, &UsersProcess::ProgressBarSetValue, this->progressBar, &QProgressBar::setValue);

    connect(this, &UsersProcess::ProcessUserRowsFinished, this->threadRowWorker.data(), &QThread::quit);
    connect(this, &UsersProcess::ProcessUserRowsFinished, this, &UsersProcess::deleteLater);
    connect(this->threadRowWorker.data(), &QThread::finished, this->threadRowWorker.data(), &QThread::deleteLater);

    this->threadRowWorker->start();
}   

void UsersProcess::OnProcessUserRowsStarted()
{
    int row = 0;

    UsersData userData(this->dbContext);

    int maxRows = this->listUsers->size();
    for(auto iter = this->listUsers->begin(); iter != this->listUsers->end(); ++iter)
    {
         row++;
         emit this->ProgressBarSetValue(row);
    }

    emit ProcessUserRowsFinished();
}

这是因为您的主题已被删除。 此调用删除 class UsersProcess 的实例,QScopedPointer 删除线程。

connect(this, &UsersProcess::ProcessUserRowsFinished, this, &UsersProcess::deleteLater);

但你也有这样的关系

connect(this, &UsersProcess::ProcessUserRowsFinished, this->threadRowWorker.data(), &QThread::quit);
connect(this->threadRowWorker.data(), &QThread::finished, this->threadRowWorker.data(), &QThread::deleteLater);

当其中一个事件触发时,线程已被删除。