
Originally Posted by
faldżip
So good solution is to make local variables in the run() method (for example instead of member variables if it is possible) so they are created in new thread and deleted when this thread ends (it ends when run() ends). So such local thread data is self cleaned on thread finish. Tadam! :]
Yes, exactly. And if you need to expose signals and slots outside you can do it like so:
public:
const Object *myInterface() const { return m_iface; }
void run() {
Object o; // lives in the worker thread, declares signals and slots
m_iface = &o;
//...
exec();
}
private:
QPointer<Object> m_iface;
};
class Thread : public QThread {
public:
const Object *myInterface() const { return m_iface; }
void run() {
Object o; // lives in the worker thread, declares signals and slots
m_iface = &o;
//...
exec();
}
private:
QPointer<Object> m_iface;
};
To copy to clipboard, switch view to plain text mode
... or the other way round (which is better as it doesn't force you to know when the thread starts):
public:
void setInterface(Object *o) { m_iface = o; }
void run() {
if(!m_iface) return; // refuse to run without the interface
Internal i;
connect(m_iface, SIGNAL(...), &i, SLOT(...)); // "m_iface" lives in the main thread, "i" lives in the worker thread
connect(&i, SIGNAL(...), m_iface, SIGNAL(...)); // propagate signal outside
//...
exec();
}
private:
QPointer<Object> m_iface;
};
class Thread : public QThread {
public:
void setInterface(Object *o) { m_iface = o; }
void run() {
if(!m_iface) return; // refuse to run without the interface
Internal i;
connect(m_iface, SIGNAL(...), &i, SLOT(...)); // "m_iface" lives in the main thread, "i" lives in the worker thread
connect(&i, SIGNAL(...), m_iface, SIGNAL(...)); // propagate signal outside
//...
exec();
}
private:
QPointer<Object> m_iface;
};
To copy to clipboard, switch view to plain text mode
Of course in the second case the QThread object can serve as "m_iface".
Bookmarks