我想在线程中通过引用来修改 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();
}
谢谢大家。