2016-12-31 43 views
0

我有以下的工人類:退出QThread的GUI應用程序退出時

class MediaWorker : public QObject 
{ 
    Q_OBJECT 
public: 
    explicit MediaWorker(QObject *parent = 0); 
    ~MediaWorker(); 

    void Exit(); 

signals: 
    void Finished(); 

public slots: 
    void OnExecuteProcess(); 
}; 

在MediaWorker.cpp

void MediaWorker::Exit() 
{ 
    emit Finished(); 
} 

void MediaWorker::OnExecuteProcess() 
{ 
    qDebug() << "Worker Thread: " << QThread::currentThreadId(); 
} 

在我的主窗口我做了以下內容:

this->threadMediaWorker = new QThread(); 
this->mediaWorker = new MediaWorker(); 
this->timerMediaWorker = new QTimer(); 
this->timerMediaWorker->setInterval(1000); 

this->timerMediaWorker->moveToThread(this->threadMediaWorker); 
this->mediaWorker->moveToThread(this->threadMediaWorker); 

connect(this->threadMediaWorker, SIGNAL(started()), this->timerMediaWorker, SLOT(start())); 
connect(this->timerMediaWorker, &QTimer::timeout, this->mediaWorker, &MediaWorker::OnExecuteProcess); 

connect(this->mediaWorker, &MediaWorker::Finished, this->threadMediaWorker, &QThread::quit); 
connect(this->mediaWorker, &MediaWorker::Finished, this->mediaWorker, &MediaWorker::deleteLater); 
connect(this->threadMediaWorker, &QThread::finished, this->mediaWorker, &QThread::deleteLater); 

this->threadMediaWorker->start(); 

的線程正常工作。當我關閉應用程序,我結束在析構函數線程:

MainWindow::~MainWindow() 
{ 
    delete ui; 

    this->mediaWorker->Exit(); 
} 

所以退出()發出信號,成品將希望刪除的QThread和mediaworker類。

我的問題是,如果這是終止線程和媒體工作者類的正確方式?

回答

1

我的問題是什麼是終止雙方 工作線程和媒體工作者階級的正確方法?

您只需確保在主窗口得到通過使用QScopedPointerstd::unique_ptr破壞了「媒體」的對象被刪除。

class MainWindow : public QMainWindow { 
    /// ... 
    QThread m_workerThread; 
    QScopedPointer<MediaWorker> m_pMediaObject; 
    /// ... 
}; 

void MainWindows::init() 
{ 
    // ... other initialization skipped ... 
    // for dynamic allocation of the object and keeping the track of it 
    m_mediaObject.reset(new MediaWorker()); 
    m_workerThread.moveToThread(m_mediaObject.data()); 
} 

void MainWindow::stopWorker() 
{ 
    if (m_workerThread.isRunning()) 
    { 
     m_workerThread.quit(); // commands Qt thread to quit its loop 
           // wait till the thread actually quits 
     m_workerThread.wait(); // possible to specify milliseconds but 
           // whether or not to limit the wait is 
           // another question 
    } 
} 

如果用於更新是有意義的嘗試停止在

void MainWindow::closeEvent(QCloseEvent *) 
{ 
    stopWorker(); 
} 

發佈的UI對象之前的工作線程但是有一個機會,在主窗口永遠不會在UI工作者線程closeEvent()破壞之前被調用,所以我們應該處理:

MainWindow::~MainWindow() 
{ 
    stopWorker(); 

    // it also destroys m_mediaObject 
} 
+0

感謝您的樣品 – adviner

+0

的[的QThread] Qt文檔(HTTP://doc.qt .io/qt-5/qthread.html#terminate)也提供了一個清晰的用例,包括首選的啓動和退出程序。 – m7913d