Pregunta

I've been trying to create a program that simulates the basic functionality of a neuron for my own amusement, and I need to decrement an integer over a period of time, so I decided to use the QTimer.

My problem is this, when my program reaches the method "changeVoltage", and the line which starts the timer, the program instantly crashes.

When the program starts, the value of volt is -40, and pressing the 'excite' button increments the voltage by 10 making it -30 by triggering changeVoltage with a value of 10. In theory, it shouldn't be recognized as higher than 50, is no longer at baseline (which if was the case would then end the timer and decrementing the voltage), but is higher than -40, which should start the timer (causing the timer to slowly decrease the volts by 1). But the timer doesn't even seem to start, as when it reaches that line, the whole program crashes.

This file goes as follows:

#include "neuron.h"
#include "ui_neuron.h"
#include "qtimer.h"

int volt = -40;
bool refract = false;
bool timerActive;

Neuron::Neuron(QWidget *parent):QWidget(parent), ui(new Ui::Neuron)
{
    ui->setupUi(this);
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(changeVoltage()),Qt::DirectConnection );
    timerActive = false;
}

Neuron::~Neuron()
{
    delete ui;
}

void Neuron::on_btnExc_clicked()
{

    changeVoltage(10);
}

void Neuron::on_btnInh_clicked()
{
    changeVoltage(-10);
}

void Neuron::changeVoltage(int c)
{
    volt = (volt + c);

    if (volt >= 50) // begin action potential
    {
        volt = volt -40;
    }

    if (volt == -40) // to not drop below -40
    {
        if (timerActive == true)
        {
            timer->stop();
        }
        volt = -40;
    }

    else if (volt >= -40)//start the timer when value changes upwards from -40
    {
        if (timerActive == false)
        {
            timerActive = true;
            timer->start(1000);
        }
    }
    ui->lblVolt->setText(QString::number(volt));
}

void Neuron::changeVoltage()
{
    changeVoltage(-1);
}

I've been debugging and trying this for hours now and cannot figure out why the QTimer isn't starting. Can it not be activated outside of the line following it being connected? Are there any other ways to achieve what I'm trying to accomplish?

¿Fue útil?

Solución

Issue is here:

QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(changeVoltage()),Qt::DirectConnection );

I assume timer is also a class member, otherwise code won't compile. In the code above you replace class member with stack variable. Fix is:

timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(changeVoltage()),Qt::DirectConnection );
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top