I\'m trying to use threads in Qt to delegate some work to a thread, but I can\'t get it to work. I have a class inheriting QMainWindow that have a member object that launch
You can also move it to your thread by doing it from the object's owner thread.
#include
#include
#include
#include
#include
#include
template
inline void runOnThread(QThread *qThread, Func &&func)
{
QTimer *t = new QTimer();
t->moveToThread(qThread);
t->setSingleShot(true);
QObject::connect(t, &QTimer::timeout, [=]()
{
func();
t->deleteLater();
});
QMetaObject::invokeMethod(t, "start", Qt::QueuedConnection, Q_ARG(int, 0));
}
void moveToThread(QObject *ptr, QThread *targetThrd=QThread::currentThread())
{
std::mutex mt;
std::condition_variable_any cv;
runOnThread(ptr->thread(),[&]
{
ptr->setParent(NULL);
ptr->moveToThread(targetThrd);
cv.notify_one();
});
cv.wait(mt);
}
You just need to call
moveToThread( m_poller, m_pollThread);