I have a QMainWindow that connects 2 buttons with 2 functions. I want to start the QTimer with the StartBTNClick function and stop the QTimer with the StopBTNClick function. My problem is, that the QTimer is not defined in StopBTNClick, that’s why I want to know how to define a public QTimer. (btw. I’m new to C++, please bear with me)
This is my code so far:
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");
}
Make the QTimer a member variable of your class, and it will be accessible in both functions.
Use the class member pointer, rather than a locally-defined one:
It would probably be better to initialize the time (runTimer = new QTimer(this) ) in the constructor rather than on a button click, and just start the timer when the button is clicked. If you don’t do it this way, you will have to guard against using an uninitialized pointer in StopBTNClick() in case that button is be clicked before the Start button.