2012-02-25 6 views
0

2つのボタンと2つの機能を接続するQMainWindowがあります。私はStartBTNClick関数でQTimerを起動し、StopBTNClick関数でQTimerを停止したいと考えています。私の問題は、QTimerがStopBTNClickで定義されていないということです。そのため、パブリックQTimerを定義する方法を知りたいのです。 (ところで、私は、私と一緒にC++への新たな負担くださいよ。)QTimerを公開します。 (Qt、C++)

これは、これまでの私のコードです:

MyClass::MainWindow(QWidget *parent, Qt::WFlags flags) 
    : QMainWindow(parent, flags) 
{ 
    ui.setupUi(this); 
    statusBar()->showMessage("Status: Idle."); 
    connect(ui.StartBTN, SIGNAL(clicked()), this, SLOT(StartBTNClick())); 
    connect(ui.StopBTN, SIGNAL(clicked()), this, SLOT(StopBTNClick())); 
} 

void MyClass::StartBTNClick() 
{ 
    QTimer *RunTimer = new QTimer(this); 
    connect(RunTimer, SIGNAL(timeout()), this, SLOT(TimerHandler())); 
    RunTimer->start(5000); 
    statusBar()->showMessage("Status: Running."); 
} 

void MyClass::StopBTNClick() 
{ 
    RunTimer->stop(); // Not working. Says it's not defined. 
    disconnect(RunTimer, SIGNAL(timeout()), this, SLOT(TimerHandler())); 
    statusBar()->showMessage("Status: Idle."); 
} 

void MyClass::TimerHandler() 
{ 
    // I set QMessageBox to test if it's working. 
    QMessageBox::information(this, "lala", "nomnom"); 
} 

答えて

3

はQTimerクラスのメンバ変数作り、それが両方にアクセスできます機能。

class MyClass 
{ 
... //other variables and method definitions 

QTimer* runTimer; 
}; 

のではなく、クラスメンバポインタを使用して1をローカルに定義された:

void MyClass::StartBTNClick() 
{ 
    runTimer = new QTimer(this);//this would work, but it may be better to 
            //initialize the timer in the constructor 
    connect(runTimer, SIGNAL(timeout()), this, SLOT(TimerHandler())); 
    runTimer->start(5000); 
    statusBar()->showMessage("Status: Running."); 
} 

void MyClass::StopBTNClick() 
{ 
    runTimer->stop(); // this will work now; if it hasn't been initialized, though, 
         // you will cause a crash. 
    disconnect(RunTimer, SIGNAL(timeout()), this, SLOT(TimerHandler())); 
    statusBar()->showMessage("Status: Idle."); 
} 

おそらくかなりコンストラクタで(runTimer =新しいQTimer(この))時間を初期化する方が良いだろうボタンをクリックするよりも、ボタンをクリックしたときにタイマーを開始するだけです。このようにしないと、Startボタンの前にボタンがクリックされた場合、StopBTNClick()で初期化されていないポインタを使用しないように注意する必要があります。

+0

今のところ魅力的な作品です。ありがとうございます。 :) QTimerが動作しているかどうかを確認するために、 'StopBTNClick'で新しいboolとifコマンドを作成しました。 ^^ – HitomiTenshi

+2

1.ブールは必要ありません。代わりにrunTimer-> isActive()を使用することができます。 2.毎回、sig/slot接続を切断する必要はありません。クラスのコンストラクタでタイマーを作成して接続する必要があります。 3.起動後にスタートボタンを無効にし、停止ボタンを有効にして、停止時にその逆を有効にすることができます。 –

+0

Kamilが正しいです。これは良い方法です。あなたがそれをやっているやり方はうまくいくかもしれませんし、特別な場合には必要かもしれませんが、おそらくあなたの場合はそうではありません – tmpearce

関連する問題