我一直在尝试创建一个程序来模拟神经元的基本功能,供我自己娱乐,我需要在一段时间内递减一个整数,所以我决定使用 QTimer。
我的问题是,当我的程序到达方法"changeVoltage"和启动计时器的行时,程序立即崩溃。
当程序启动时,伏特的值为 -40,按下"激励"按钮通过触发值为 10 的 changeVoltage 将电压增加 10,使其成为 -30。从理论上讲,它不应该被识别为高于 50,不再处于基线(如果是这种情况,那么将结束计时器并降低电压),而是高于 -40,这应该启动计时器(导致计时器缓慢降低伏特 1)。但是计时器似乎甚至没有启动,因为当它到达该行时,整个程序都会崩溃。
此文件如下所示:
#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);
}
我已经调试并尝试了几个小时,但无法弄清楚为什么 QTimer 无法启动。连接后不能在线路外激活吗?还有其他方法可以实现我想要实现的目标吗?
问题在这里:
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(changeVoltage()),Qt::DirectConnection );
我假设计时器也是一个类成员,否则代码将无法编译。在上面的代码中,您将类成员替换为堆栈变量。修复是:
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(changeVoltage()),Qt::DirectConnection );