一个练手的小项目。首先想要有一个界面类,一个控制时间倒数的类。这个类可以每隔一秒通知界面类更新。这里用信号槽的方式设置一个timer每秒钟在它的interval里进行秒数减一,然后把这个秒数用信号的方式传递给界面类。界面类的slot函数根据秒数计算出相应的小时分钟和秒数,然后显示。
界面:
直接拖的
控制时间的timecontrol类有ready start和end三个功能:给到界面类之后,界面类用它的方法对时间进度进行控制。这里发出freshSignal信号由界面类接收
#include "timecontrol.h"
TimeControl::TimeControl(QObject *parent) : QObject(parent)
{
this->s=0;
}
void TimeControl::on_timer_out(){
this->s--;
emit freshSignal(s);
}
void TimeControl::readyCount(int s){
this->s=s;
fTimer=new QTimer(this);
fTimer->stop();
fTimer->setInterval(1000);
connect(fTimer,SIGNAL(timeout()),this,SLOT(on_timer_out()));
}
void TimeControl::startcount(){
fTimer->start();
}
void TimeControl::endcount(){
fTimer->stop();
}
界面类如下主要的功能是根据秒数解析小时和分钟数,以及对相关按钮的槽函数编写
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)//类的初始化列表
{
ui->setupUi(this);//this表示当前类
this->tc=new TimeControl();
connect(tc,SIGNAL(freshSignal(int)),this,SLOT(showCurrentSecond(int)));
}
void MainWindow::showCurrentSecond(int s){
if(s<=0){
tc->endcount();
ui->startTime->setEnabled(true);
ui->endTime->setEnabled(false);
}
//获得小时
int h=0,m=0;
h=s/3600;
s%=3600;
m=s/60;
s%=60;
ui->lcdhour->display(h);
ui->lcdminute->display(m);
ui->lcdsecond->display(s);
}
MainWindow::~MainWindow()//析构函数
{
delete ui;
}
void MainWindow::on_startTime_clicked()
{
int second= ui->textEdit->toPlainText().toInt();
qDebug()<<QString(second);
tc->readyCount(second);
tc->startcount();
ui->startTime->setEnabled(false);
ui->endTime->setEnabled(true);
}
void MainWindow::on_endTime_clicked()
{
tc->endcount();
ui->startTime->setEnabled(true);
ui->endTime->setEnabled(false);
}
最后是主类:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
虽然是很简单的一个程序,但是尽量遵循显示和逻辑分开的原则,实现这个可以直接用LCD控件,这里主要也是练习一下信号槽的使用。
完整代码:https://github.com/kisstherain8677/QTPractice