通过引用线程传递值并进行修改

时间:2013-08-14 13:07:15

标签: c++ qt

我想在线程中通过引用修改Qlist,因为排序可能需要几秒钟。

但似乎我无法修改List。在线程之外,List没有改变。

在QMainwindow:

QThread *thread = new QThread();
    FarmSortWorker *farmsort_worker = new FarmSortWorker();
    farmsort_worker->setFarmData(farm_list);
    farmsort_worker->moveToThread(thread);

    connect(farmsort_worker, &FarmSortWorker::error, [=](QString error_msg){
        qDebug() << error_msg;
        logger->logEvent(error_msg, Logger::ERROR);
    });
    connect(thread, &QThread::started, farmsort_worker, &FarmSortWorker::processSort);
    connect(farmsort_worker, &FarmSortWorker::finished, thread, &QThread::quit);
    connect(farmsort_worker, &FarmSortWorker::finished, farmsort_worker, &QThread::deleteLater);
    connect(thread, &QThread::finished, thread, &QThread::deleteLater);
    thread->start();

我的主题(.h)

#ifndef FARMSORTWORKER_H
#define FARMSORTWORKER_H

#include <QObject>
#include "../framcontainer.h"

#include <QList>
#include <qDebug>
#include <QString>

class FarmSortWorker : public QObject
{
    Q_OBJECT
public:
    explicit FarmSortWorker(QObject *parent = 0);
    ~FarmSortWorker();
    void setFarmData(QList<FramContainer> &farm_container);

private:
    QList<FramContainer> farm_container;

signals:
    void error(QString error);
    void finished();

public slots:
    void processSort();

};

#endif // FARMSORTWORKER_H

我的主题(.cpp)

#include "farmsortworker.h"

FarmSortWorker::FarmSortWorker(QObject *parent) :
    QObject(parent)
{
}

FarmSortWorker::~FarmSortWorker()
{
}


void FarmSortWorker::setFarmData(QList<FramContainer> &farm_container)
{

    this->farm_container = farm_container;
}


void FarmSortWorker::processSort()
{
    qDebug() << "count:" << farm_container.size();
    for(int i = 0; i < farm_container.size(); i++)
    {

        FramContainer park = farm_container.at(i);
        qDebug() << "original:" << park.getFarmName();

    }
    for(int i = 0; i < farm_container.size(); i++)
    {
        FramContainer *park =& farm_container[i];
        park->setFarmName("test");


    }
    for(int i = 0; i < farm_container.size(); i++)
    {

        FramContainer park = farm_container.at(i);
        qDebug() << "neu:" << park.getFarmName();

    }

    emit finished();
}

提前谢谢大家。

1 个答案:

答案 0 :(得分:3)

这是因为您在线程类中保存了列表的副本,而不是参考。

不是使用单独的函数来设置列表,而是将其(通过引用)传递给构造函数,并让它设置引用变量:

class FarmSortWorker : public QObject
{
    Q_OBJECT
public:
    explicit FarmSortWorker(QList<FramContainer>& list, QObject *parent = 0);

    ...

private:
    QList<FramContainer>& farm_container;  // Store as a reference

    ...
};

...

FarmSortWorker::FarmSortWorker(QList<FramContainer>& list, QObject *parent) :
    QObject(parent), farm_container(list)
{
}

...

QThread *thread = new QThread();
FarmSortWorker *farmsort_worker = new FarmSortWorker(farm_list);

...