新建一个线程,让某个类在新线程中执行的方法

/*myMoveToThread
 * usage:
 * class A:public QObject
 * A *a;//exec in current thread
 * class OtherClass:public QObject
 * OtherClass *otherClass;//exec in new thread
 * connect(a,&A::someSignal,otherClass,&OtherClass::someSlot);
 * connect(otherClass,&OtherClass::someSignal,a,&A::someSlot);
 * //Critical(Next Line)!!! otherClass MUST HAVE A PATH TO DESTROY
 * connect(a,&A::destroyed,otherClass,&OtherClass::deleteLater);
 * myMoveToThread(otherClass);
 *
 * Then class named otherClass is running at a new Thread.
 * While otherClass destroyed(),then the new thread will be deleted.
 * Otherwise,the new thread never quit,even though application exit.
*/
void dlgCfgTrans::myMoveToThread(QObject *t)
{
    QThread *otherThread = new QThread();
    t->moveToThread(otherThread);
    connect(t,&QObject::destroyed,otherThread,&QThread::quit);
    connect(otherThread,&QThread::finished,otherThread,&QThread::deleteLater);
    otherThread->start();
    //hasThread = true;
}
posted @ 2021-05-21 15:12  有没有的有  阅读(219)  评论(0)    收藏  举报