q2110809471 2023-03-26 20:13 采纳率: 38.5%
浏览 29

qt定时器启动不了啊,如何解决?



Didlog::Didlog(QWidget* parent):QDialog(parent)
{
  
    ui.setupUi(this);
  
    QTimer *fTimer = new QTimer(this);
    fTimer->stop();
    fTimer->setInterval(1000);
    connect(fTimer, SIGNAL(timeout()), this, SLOT(on_timer_timeout()));
     connect(ui.btnStart, SIGNAL(clicked()),this, SLOT(on_btnStart_clicked()));
     connect(ui.btnStop, SIGNAL(clicked()), ui.LabElapsTime, SLOT(on_btnStop_clicked()));
}



void Didlog::on_timer_timeout()
{
  
    QTime curTime = QTime::currentTime();
    ui.LCDHour->display(curTime.hour());
    ui.LCDMin->display(curTime.minute());
    ui.LCDSec->display(curTime.second());
    int va = ui.progressBar->value();
    va++;
    while (va > 100)
    {
        va = 0;
        ui.progressBar->setValue(va);
    }
}

void Didlog::on_btnStart_clicked()
{
    fTimer->start();
    fTimeCounter.start();
    ui.btnStart->setEnabled(false);
    ui.btnStop->setEnabled(true);

}

void Didlog::on_btnStop_clicked()
{
    std::cout << "看的到吗" <<std:: endl;
    fTimer->stop();
    int tmMsec = fTimeCounter.elapsed();
    int ms = tmMsec % 1000;
    int sec = tmMsec/1000;
    QString str = QString::asprintf("看的到吗?");//("流逝时间为: %d 秒, %d 毫秒",sec, ms);
    ui.LabElapsTime->setText(str);
    ui.btnStart->setEnabled(true);
    ui.btnStop->setEnabled(false);

}
Didlog::~Didlog()
{
    delete(fTimer);
}
`


```}
  • 写回答

2条回答 默认 最新

  • IT_service_mesh 2023-03-26 20:40
    关注

    参考GPT和自己的思路:根据您提供的代码,在 Didlog 类的构造函数中,您创建了一个 QTimer 对象 fTimer,但是您在定义 Didlog 类的成员函数 on_btnStart_clicked() 和 on_btnStop_clicked() 中使用的 fTimer 变量与类成员变量 fTimer 不同,导致 fTimer 无法启动。您需要将 fTimer 定义为类的成员变量,修改 Didlog 类的构造函数如下:

    Didlog::Didlog(QWidget* parent) : QDialog(parent)
    {
        ui.setupUi(this);
    
        fTimer = new QTimer(this);
        fTimer->stop();
        fTimer->setInterval(1000);
        connect(fTimer, SIGNAL(timeout()), this, SLOT(on_timer_timeout()));
        connect(ui.btnStart, SIGNAL(clicked()), this, SLOT(on_btnStart_clicked()));
        connect(ui.btnStop, SIGNAL(clicked()), ui.LabElapsTime, SLOT(on_btnStop_clicked()));
    }
    

    值得注意的是,修改后的 Didlog 声明了一个 QTimer 成员变量 fTimer,可以在 Didlog 类中的任何成员函数中访问它。

    另外,您的 while 循环可能会导致程序陷入死循环,建议将它改为 if 语句:

    if (va > 100)
    {
        va = 0;
    }
    ui.progressBar->setValue(va);
    va++;
    
    评论

报告相同问题?

问题事件

  • 创建了问题 3月26日

悬赏问题

  • ¥15 SQLServer怎么录入下标
  • ¥100 无网格伽辽金方法研究裂纹扩展的程序
  • ¥15 错误于library(org.Hs.eg.db): 不存在叫‘org.Hs.eg.db’这个名称的程序包,如何解决?
  • ¥60 求一个图片处理程序,要求将图像大小跟现实生活中的大小按比例联系起来的
  • ¥50 求一位精通京东相关开发的专家
  • ¥100 求懂行的大ge给小di解答下!
  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活