2013-04-12 27 views
1

的我在Qt的練習線程。我重新實現run()(雖然不推薦),一切正常。重新實現的start()的QThread

現在我想讓run()增加一些功能,讓它通過一個變量:run(int i)。 此外,我想start(),它調用運行,給一個變量傳遞給run(int i)start(int j)


我想通過以下方式重新實現啓動應該工作:(ZAEHLER是的QThread)

void Zaehler::start(int ZaehlerIndex) { run(ZaehlerIndex), terminate(); }

那麼它沒有。我的GUI在啓動線程時凍結。


問題: 我知道,有啓動和運行應避免搞亂,但有沒有辦法做到這一點?難道我做錯了什麼?

備註: 我擡頭qthread.cpp怎麼看start()實現,但所有我發現了

\sa run(), terminate()這是註釋掉!所以它實際上不應該工作!?

+0

你解決了你的問題嗎? – loentar

回答

0

怎麼這樣呢?

class Worker 
{ 
    //note, only pass parameters by copy here. 
    public: 
     Worker(int param) : myParam(param) {} 

    public slots: 
     void process() 
     { 
      //do something with myParam here, it will run in the thread. 
     } 

    signals: 
     void finished(); 
     void error(QString err); 

    private: 
     int myParam; 
}; 

然後可以掛接到使用「moveToThread」像這樣一個線程對象:

QThread* thread = new QThread; 
Worker* worker = new Worker(5); 
worker->moveToThread(thread); 
connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString))); 
connect(thread, SIGNAL(started()), worker, SLOT(process())); 
connect(worker, SIGNAL(finished()), thread, SLOT(quit())); 
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); 
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); 
thread->start(); 

在這裏看到更多信息和Qt中的線程使用一個簡短的教程: http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/

0

如果你想開始內螺紋的功能和傳遞一些參數這個功能我會建議使用此方法:

class MyWorker: public QThread 
{ 
    Q_OBJECT 
public: 
    MyWorker() 
    { 
     start(); 
    } 

    virtual ~MyWorker() 
    { 
     quit(); 
     wait(); 
    } 

    // your function to call inside thread 
    Q_INVOKABLE void doSomeWork(int data) 
    { 
     // check if we called from another thread 
     if (QThread::currentThread() != this) 
     { 
      // re-call self from very own thread 
      QMetaObject::invokeMethod(this, "doSomeWork", 
             Qt::BlockingQueuedConnection, 
      // or Qt::QueuedConnection if you want to start it asynchronously 
      // and don't wait when work finished 
             Q_ARG(int, data)); 
      return; 
     } 

     // this will be started within your thread 
     // some useful work here 
    } 
}; 

如果你的線程有沒有run()方法QEventLoop將被使用,你可以回憶你的方法在線程上下文中。

而且不是Q_INVOKABLE你可以宣佈你的方法插槽和使用隊列連接調用它。