首页| 论坛| 消息

标题:十、Qt Creator中实现定时器和产生随机数(原创)
作者:yafei86
日期:2009-11-10 11:53
内容:

有两种方法实现定时器。
第一种。自己建立关联。
1.新建Gui工程,工程名可以设置为timer。并在主界面上添加一个标签label,并设置其显示内容为“0000-00-00 00:00:00 星期日”。
2.在mainwindow.h中添加槽函数声明。
private slots:
void timerUpDate();
3.在mainwindow.cpp中添加代码。
添加#include 的头文件包含,这样就包含了QtCore下的所有文件。
构造函数里添加代码:
QTimer *timer = new QTimer(this);
//新建定时器
connect(timer,SIGNAL(timeout()),this,SLOT(timerUpDate()));
//关联定时器计满信号和相应的槽函数
timer->start(1000);
//定时器开始计时,其中1000表示1000ms即1秒
4.然后实现更新函数。
void MainWindow::timerUpDate()
{
QDateTime time = QDateTime::currentDateTime();
//获取系统现在的时间
QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
//设置系统时间显示格式
ui->label->setText(str);
//在标签上显示时间
}
5.运行程序,效果如下。

第二种。使用事件。(有点像单片机中的定时器啊)
1.新建工程。在窗口上添加两个标签。
2.在main.cpp中添加代码,实现中文显示。
#include
QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
3.在mainwindow.h ..

回复 发表
主题 版块