2009-10-27 186 views
0

好了,所以我有這個問題今晚:Qt4的啓動和停止(暫停)

[...] 

connect(startButton, SIGNAL(clicked()), this, SLOT(startCalculation())); 
connect(stopButton, SIGNAL(clicked()), this, SLOT(stopCalculation())); 

[...] 

void MainWindow::startCalculation() 
{ 
    qDebug() << "hello"; 
    this->startButton->setDisabled(true); 
    this->stopButton->setEnabled(true); 
    this->calcStatus = true; 
    this->calculate(); 
} 

void MainWindow::stopCalculation() 
{ 
    this->startButton->setEnabled(true); 
    this->stopButton->setDisabled(true); 
    this->calcStatus = false; 
} 


void MainWindow::calculate() 
{ 
    qDebug() << "hello"; 
    while(this->calcStatus) 
    { 
    } 
} 
[...] 

我試圖使計算()過程可能停止的任何時間,但它開始我之後鬆散的控制,我不能按停止。當然,在我未來的計劃中,計算()將「計算」一些真實的東西(例如傳熱模擬)。

感謝您的建議。 P.

回答

0

您需要考慮線程。計算鎖定用戶界面。

0

那麼,在「概論設計C++與Qt4的模式」,他們說,

「有可能避免贊成Qt的事件循環 的使用 線程與QTimers結合」

,但我從來沒有嘗試過:)

其實,我只是試着 -

添加:

在MainWindow類報頭和在主窗口構造附加
QTimer  *Timer; 

Timer = new QTimer(this); 

然後改變計算()從函數到的信號,並修改:

void MainWindow::startCalculation() 
{ 
    qDebug() << "hello"; 
    this->startButton->setDisabled(true); 
    this->stopButton->setEnabled(true); 
    this->calcStatus = true; 
    connect(Timer, SIGNAL(timeout()), this, SLOT(calculate())); 
    Timer->start(0); 
} 

void MainWindow::stopCalculation() 
{ 
    this->startButton->setEnabled(true); 
    this->stopButton->setDisabled(true); 
    this->calcStatus = false; 
    Timer->stop(); 
    Timer->disconnect(this,SLOT(calculate())); 
} 

這應該工作只要你不將任何參數傳遞給calculate()。

+0

如果你可以將計算分解成離散的步驟,並且在需要繼續計算任何值時重複調用計時器函數,那麼這種方法纔有效。另外,您不需要保留QTimer指針...... QTimer內部有一個方便的函數來執行此操作:「QTimer :: singleshot(0,this,SLOT(calculate());」。 – 2009-10-27 17:16:50