PDA

View Full Version : public timer sometimes crashes at runtime



twoten
25th February 2016, 04:00
I'm building a timer with an interval that can adjusted by a slider. Here's a shot of my ui:

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



#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
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



#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qapplication.h"
#include <QtWidgets>

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

QTimer *timer = new QTimer(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?

anda_skoa
25th February 2016, 10:02
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,
_

twoten
25th February 2016, 14:51
Can you give me an example of the correct way to do this?

Lesiok
25th February 2016, 15:43
Initialize the timer before the initialization ui.

anda_skoa
25th February 2016, 15:54
Can you give me an example of the correct way to do this?
Instead of


QTimer *timer = new QTimer(this);

you write


timer = new QTimer(this);


Cheers,
_

twoten
25th February 2016, 16:13
Fantastic! Not only did it work but I also understand why! Thank you very much!