The issue here is that you are using a reference for your signal/slot, i.e. a QList<QString> &
. This is not compatible with threads since they use their own private stack, and in this case what you do is passing a pointer to an object in the stack from one thread to another.
Possibilities are:
- Use raw
QList<QString>
signals/slots, that will force a copy. - Allocate the
QList<QString>
with anew
(hence will go in the heap instead of the stack), and useQList<QString> *
signals/slots.
The following code illustrates these two methods:
// A.h
#include <QObject>
#include <QDebug>
class A: public QObject
{
Q_OBJECT
public slots:
void foo(int i) { qDebug() << i; }
void bar(QList<int> l) { foreach(int i, l) qDebug() << i; }
void bar2(QList<int> * l) { foreach(int i, *l) qDebug() << i; }
};
// Worker.h
#include <QObject>
class Worker: public QObject
{
Q_OBJECT
public slots:
void process()
{
// pass an int
emit foo(1);
// pass a list by value
emit bar(QList<int>() << 2 << 3 << 4);
// pass a poniter to a list
list = new QList<int>();
*list << 5 << 6 << 7;
emit bar2(list);
emit finished();
}
signals:
void finished();
void foo(int);
void bar(QList<int>);
void bar2(QList<int> *);
private:
QList<int> * list;
};
// main.cpp
#include <QApplication>
#include <QThread>
#include <QObject>
#include "A.h"
#include "Worker.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
A * a = new A();
Worker * worker = new Worker();
QObject::connect(worker, SIGNAL(foo(int)), a, SLOT(foo(int)));
QObject::connect(worker, SIGNAL(bar(QList<int>)), a, SLOT(bar(QList<int>)));
QObject::connect(worker, SIGNAL(bar2(QList<int>*)), a, SLOT(bar2(QList<int>*)));
QThread * thread = new QThread();
worker->moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), worker, SLOT(process()));
QObject::connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
QObject::connect(thread, SIGNAL(finished()), &app, SLOT(quit()));
thread->start();
return app.exec();
}
Output:
1
2
3
4
5
6
7