1.在QTcreator中实现定时器功能,主要是了解QTimer类的使用,这个给出一个例子,实现时间的刷新,以秒为单位。
主要有3个文件,分别是
1).main.cpp
2).mainwindow.cpp
主要有3个文件,分别是
1).main.cpp
2).mainwindow.cpp
3).mainwindow.h
2.贴代码
1).mian.cpp代码如下:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
2).mianwindow.cpp代码如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCore>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTimer *timer=new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(ShowTimeDate()));
timer->start(1000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::ShowTimeDate()
{
QDateTime datetime = QDateTime::currentDateTime();
QString str = datetime.toString("yyyy-MM-dd hh:mm:ss ddd");
ui->label->setText(str);
}
3).mainwindow.h代码如下:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
void ShowTimeDate(void);
};
#endif // MAINWINDOW_H
3. 运行结果如下: