繁体   English   中英

以单独的方法启动时QTimer崩溃

[英]QTimer crashes when started in separate method

我一直在尝试创建一个程序来模拟神经元的基本功能以供我自己娱乐,我需要在一段时间内递减一个整数,所以我决定使用QTimer。

我的问题是这样,当我的程序到达方法“changeVoltage”,以及启动计时器的行时,程序立即崩溃。

当程序启动时,伏特的值为-40,按下“激励”按钮将电压增加10,使其变为-30,触发changeVoltage,值为10.理论上,它不应被认为高于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也是一个类成员,否则代码将无法编译。 在上面的代码中,使用堆栈变量替换类成员。 修复是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM