2012-02-25 2 views
0

2 개의 버튼과 2 개의 기능을 연결하는 QMainWindow이 있습니다. StartBTNClick 기능으로 QTimer를 시작하고 StopBTNClick 기능으로 QTimer를 중지하고 싶습니다. 내 문제는 QTimer가 StopBTNClick에 정의되어 있지 않다는 것입니다. 그래서 공개 QTimer를 정의하는 방법을 알고 싶습니다.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 클래스의 멤버 변수 확인하고 그것을 모두에서 액세스 할 수 있습니다 :

이 지금까지 내 코드입니다. (BTW 나는 C++에 새로 온 사람, 나와 함께 곰하시기 바랍니다) 기능.

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

QTimer* runTimer; 
}; 

보다는, 클래스 멤버 포인터를 사용하여 한을 로컬로 정의 된 :

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. bool이 필요 없으므로 대신 runTimer-> isActive()를 사용할 수 있습니다. 2. 매회 시그널/슬롯 연결을 끊을 필요가 없습니다. 당신은 클래스 생성자에서 타이머를 만들고 연결해야합니다. 3. 시작 후 시작 버튼을 사용 중지하고 중지 버튼을 사용 중지 할 수 있습니다. –

+0

Kamil이 정확합니다.이 방법이 더 좋습니다. 당신이하고있는 방식은 효과가있을 수 있으며 특수한 경우에는 필요할 수도 있지만 귀하의 경우에는 그렇지 않을 수도 있습니다. – tmpearce