1 Attachment(s)
public timer sometimes crashes at runtime
I'm building a timer with an interval that can adjusted by a slider. Here's a shot of my ui:
Attachment 11739
The upper lcdNumber counts up by one every second. I want to use the slider to speed it up and slow it down. Here is my header file
Code:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
{
Q_OBJECT
public:
explicit MainWindow
(QWidget *parent
= 0);
~MainWindow();
QTimer *timer;
// here the timer is made public
private:
Ui::MainWindow *ui;
private slots:
void inkup();
void on_horizontalSlider_valueChanged(int value);
};
#endif // MAINWINDOW_H
And here is my application
Code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qapplication.h"
#include <QtWidgets>
MainWindow
::MainWindow(QWidget *parent
) : ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(timer, SIGNAL(timeout()), this, SLOT(inkup()));
timer->start(1000);
}
void MainWindow::inkup() {
int eks = ui->lcdNumber->value();
eks += 1;
ui->lcdNumber->display(eks);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_horizontalSlider_valueChanged(int speed)
{
ui->lcdNumber_2->display(timer->remainingTime());
ui->lcdNumber_2->display(speed);
timer->setInterval(speed); // this causes a crash at run time
}
In the horizontal slider event handler, I can display in the second lcdNumber the timer property remainingTime(). No problem. I can display the changed slider value so I know it's okay. But when I try and set the timer interval I get a run time crash. In fact most of the properties that pop up for the timer when I type timer-> also cause a crash. What am I doing wrong?
Re: public timer sometimes crashes at runtime
Quote:
Originally Posted by
twoten
But when I try and set the timer interval I get a run time crash. In fact most of the properties that pop up for the timer when I type timer-> also cause a crash. What am I doing wrong?
Because you are accessing an uninitialized pointer.
Your member variable "timer" never gets initialized, so it points to some random memory address.
Your constructor initializes a local variable with the same name, so you probably didn't want this to be a local variable.
Cheers,
_
Re: public timer sometimes crashes at runtime
Can you give me an example of the correct way to do this?
Re: public timer sometimes crashes at runtime
Initialize the timer before the initialization ui.
Re: public timer sometimes crashes at runtime
Quote:
Originally Posted by
twoten
Can you give me an example of the correct way to do this?
Instead of
you write
Cheers,
_
Re: public timer sometimes crashes at runtime
Fantastic! Not only did it work but I also understand why! Thank you very much!