
用QTimer或者QBasicTimer
QTimer主要就是为计时而设计,QTimer类使用起来也很简单。举个小例子
假设构造函数有如下代码
QTimer timer = new QTimer(this);
timer->setInterval(1000); //1000ms == 1s
connect(timer,SIGNAL(timeout()),this,SLOT(display()));
对应的槽函数display定义如下
void MainWindow::display()
{
static int count = 0;
//增加时间计数
count++;
//显示当前的时间计数
label->setText(QString::number(count));
}
上面的代码就已经完成了你的要求。每间隔1秒,count就会加1,也就是说label上显示的数字为当前程序运行了多少秒。
QBasicTimer属于轻量级的计时类,它不继承自QObject,所以它不能给你提供信号和槽。
QBasicTimer的用法如下:
假设你头文件有如下定义
protected:
void timerEvent(QTimerEvent );
private:
QBasicTimer timer;
构造函数有如下调用
timerstart(1000,this);
最后重新实现的timerEvent函数如下
void MainWindow::timerEvent(QTimerEvent event)
{
static int count = 0;
if (event->timerId() == timertimerId()) {
//增加时间计数
count++;
//显示当前的时间计数
label->setText(QString::number(count));
} else {
QWidget::timerEvent(event);
}
}
上面两种方式都可以实现你的要求,相比之下QBasicTimer更适合在嵌入式设备上进行使用。
我看到你的问题,我做了一个只显示时间的,是在窗口标题里显示,我的秒钟会走动啊。
你把代码改一下。
我的代码是这样的
void mainWidget::timerEvent(QTimerEvent event)
{
if(event->timerId()==myTimerID)
{
time=QTime::currentTime();
setWindowTitle(tr("%1:%2:%3")arg(timehour())arg(timeminute())arg(timesecond()));
}
}
myTimerID声明为int 类型,
在构造函数里加入myTimerID=startTimer(1000);
我想你是没有加入if(event->timerId()==myTimerID)
进行判断。
QDateTime dateTime () const,调用这个得到控件的时间,然后判断是否是你要的时间,然后就做相应的事。或者这个信号:timeChanged( const QTime & time );
以上就是关于QT 如何实现记录运行时间全部的内容,包括:QT 如何实现记录运行时间、qt mainwindow中如何刷新系统时间、qt QDateTimeEdit想要取其中一段时间怎么办等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)