Qt 定時器Timer使用


From: http://dragoon666.blog.163.com/blog/static/107009194201092602326598/

1.新建Gui工程,在主界面上添加一個標簽label,並設置其顯示內容為“0000-00-00 00:00:00 星期日”。

2.在mainwindow.h中添加槽函數聲明。

private slots:

void timerUpDate();

3.在mainwindow.cpp中添加代碼。

添加#include <QtCore>的頭文件包含,這樣就包含了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.運行程序。

======================================================

以下是本人自己整理的代碼:

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:
	void timerEvent(QTimerEvent *);

private:
    Ui::MainWindow *ui;

private slots:
    void on_btnLogin_clicked();
#if 0
	void timerUpDate();
#endif
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include <QMessageBox>
#include <QtCore>
#include <time.h>
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
#if 0
	QTimer *timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(timerUpDate()));
	timer->start(1000);
#else
	qsrand(time(0));
	startTimer(1000);		// 返回值為1, 即timerId
	startTimer(5000);		// 返回值為2
	startTimer(10000);		// 返回值為3
#endif
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btnLogin_clicked()
{
	QMessageBox::information(this, "Caption", tr("Hello你好嗎"), QMessageBox::Ok);
}

#if 0
void MainWindow::timerUpDate()
{
	QDateTime time = QDateTime::currentDateTime();
	QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
	ui->lblCurDate->setText(str);
}
#else
void MainWindow::timerEvent(QTimerEvent *t)
{
	switch(t->timerId())
	{
	case 1:
		{
			QDateTime time = QDateTime::currentDateTime();
			QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
			ui->lblCurDate->setText(str);
			ui->lbl1->setText(tr("每秒產生一個隨機數: %1").arg(qrand() % 10));
			ui->lbl1->adjustSize();
		}
		break;
	case 2:
		ui->lbl2->setText(tr("5秒后軟件將關閉"));
		ui->lbl2->adjustSize();
		break;
	case 3:
		qApp->quit();		// 退出系統
		break;
	}
}

#endif

main.cpp

#include <QtGui/QApplication>
#include <QTextCodec>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
	QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    MainWindow w;
    w.show();

    return a.exec();
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM