1

我有以下代码按预期工作。它更新每个 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();
}
4

1 回答 1

1

这是因为您的帖子已被删除。此调用删除类 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);

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

于 2015-12-29T14:24:03.080 回答