I have a small worker thread:
class ReloadDirectoryThread
: public QThread{
Q_OBJECT
public:
ReloadDirectoryThread()
};
~ReloadDirectoryThread() {
};
void run() {
exec();
};
public slots:
void importImage
(int row,
QString filePath
);
signals:
void imageImported
(int row,
QIcon* icon
);
};
class ReloadDirectoryThread : public QThread
{
Q_OBJECT
public:
ReloadDirectoryThread()
: QThread() {
};
~ReloadDirectoryThread() {
};
void run() {
exec();
};
public slots:
void importImage(int row, QString filePath);
signals:
void imageImported(int row, QIcon* icon);
};
To copy to clipboard, switch view to plain text mode
Its task is to open Images pointed to by filePath, convert them into a QIcon and emit each new Icon:
void ReloadDirectoryThread
::importImage(int row,
QString filePath
) {
emit imageImported(row, icon);
}
void ReloadDirectoryThread::importImage(int row, QString filePath)
{
QIcon* icon = new QIcon(QPixmap(filePath));
emit imageImported(row, icon);
}
To copy to clipboard, switch view to plain text mode
The thread will be started from the main-application thread:
{ ...
reloadDirectoryThread = new ReloadDirectoryThread;
connect(this,
SIGNAL(importImage
(int,
QString)),
reloadDirectoryThread,
SLOT(importImage
(int,
QString)), Qt
::QueuedConnection);
connect(reloadDirectoryThread,
SIGNAL(imageImported
(int,
QIcon*)),
this,
SLOT(imageImported
(int,
QIcon*)), Qt
::QueuedConnection);
reloadDirectoryThread->moveToThread(reloadDirectoryThread);
reloadDirectoryThread->start();
...}
{ ...
reloadDirectoryThread = new ReloadDirectoryThread;
connect(this, SIGNAL(importImage(int,QString)),
reloadDirectoryThread, SLOT(importImage(int,QString)), Qt::QueuedConnection);
connect(reloadDirectoryThread, SIGNAL(imageImported(int,QIcon*)),
this, SLOT(imageImported(int,QIcon*)), Qt::QueuedConnection);
reloadDirectoryThread->moveToThread(reloadDirectoryThread);
reloadDirectoryThread->start();
...}
To copy to clipboard, switch view to plain text mode
The Thread should be shut down when closing the app:
{...
reloadDirectoryThread->quit();
reloadDirectoryThread->wait(3000);
delete reloadDirectoryThread;
...}
{...
reloadDirectoryThread->quit();
reloadDirectoryThread->wait(3000);
delete reloadDirectoryThread;
...}
To copy to clipboard, switch view to plain text mode
This will tell the thread to quit its eventLoop and waits at most 3 seconds for the thread to finish. At this time all "importImage"-signals are already posted into the event queue.
My problem is that the worker-thread always completes all messages (what in fact lasts more than three seconds) until the Thread Object can be deleted safely.
Any ideas what's going wrong ? Why does the thread not stop executing events from the eventqueue when calling quit() ?
.. frank
Bookmarks