1

我试图让一个文本编辑框使用 QTimer 每 5 秒显示一次当前时间。我在一个单独的方法中计算了当前时间,然后让 QTimer 调用该方法并显示当前时间。我一生都无法弄清楚如何将变量从 setCurrentTime 方法传递给 QTimer。我确定这是一个非常容易解决的问题,但我无法弄清楚。这是我的代码。

void noheatmode::setCurrentTime()
{
   QTime time = QTime::currentTime();
   QString sTime = time.toString("hh:mm:mm");
   // ui->tempTimeNoHeatMode->append(sTime);

}

void noheatmode::on_timeButton_clicked()
{


    QTimer *timer =new QTimer(this);
    connect(timer,SIGNAL(timeout()), this, SLOT(setCurrentTime()));
    timer->start(5000);
    ui->tempTimeNoHeatMode->append(sTime);
}
4

2 回答 2

0

如果我的问题是正确的,那么您只有分钟变量而不是秒。只需将“hh:mm:mm”更改为“hh:mm:ss”

void noheatmode::setCurrentTime()
{
    QTime time = QTime::currentTime();
    QString sTime = time.toString("hh:mm:ss");
    ui->tempTimeNoHeatMode->append(sTime);
}
于 2015-06-11T16:46:56.457 回答
0

使用您的代码:

void noheatmode::on_timeButton_clicked()
{
    QTimer *timer =new QTimer(this);
    connect(timer,SIGNAL(timeout()), this, SLOT(setCurrentTime()));
    timer->start(5000);
    ui->tempTimeNoHeatMode->append(sTime);
}

这意味着其中的函数SLOT将每5000毫秒调用一次,即 5 秒。然后可以做的是,您将函数设置setCurrentTime()为每次调用时更新您的文本框。

例子:

void Class::setCurrentTime()
{
    QTime times = (QTime::currentTime());
    QString currentTime=times.toString("hh:mm:ss");
    ui->label->setText(currentTime); 
    //Assuming you are using a label to output text, else substitute for what you are using instead
    //Every time this function is called, it will receive the current time 
    //and update label to display the time received
}
于 2015-06-11T19:00:38.320 回答