1

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

但似乎我无法修改列表。在线程之外,列表尚未更改。

在 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();
}

谢谢大家。

4

1 回答 1

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);

...
于 2013-08-14T13:11:03.417 回答