主要任务:
设计一个电子相册,点击上一张,切换到上一张图片,点击下一张,切换到下一张图片。
点击开始播放,图片循环播放,点击结束播放,图片停止播放。
设计方法:
使用QList存储各个图片的资源路径,QTimer定时器控制循环播放间隔时间。
添加图片到项目目录中
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
//头文件
#include<QList>
#include<QTimer>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
private:
Ui::Dialog *ui;
QList<QString> list;
int count=0;
QTimer *timer;
private slots://槽函数
void clickPeriousSlot();//点击上一张
void clickNextSlot();//点击下一张
void clickStartSlot();//开始播放
void clickEndSlot();//结束播放
void timeoutSlot();
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
//创建定时器对象
timer=new QTimer(this);
//设置间隔时间
timer->setInterval(1000);
//设置周期性 true:单次性 false:周期性
timer->setSingleShot(false);
connect(timer,SIGNAL(timeout()),this,SLOT(timeoutSlot()));
//设置图片
QString img1(":/new/prefix1/flower.jpg");
QString img2(":/new/prefix1/grass.jpeg");
QString img3(":/new/prefix1/sand.jpeg");
QString img4(":/new/prefix1/tree.jpg");
QString img5(":/new/prefix1/water.jpg");
//将图片以向后追加的方式存放到QList中
list.push_back(img1);
list.push_back(img2);
list.push_back(img3);
list.push_back(img4);
list.push_back(img5);
//连接槽函数
connect(ui->pushButtonUp,SIGNAL(clicked()),this,SLOT(clickPeriousSlot()));
connect(ui->pushButtonNext,SIGNAL(clicked()),this,SLOT(clickNextSlot()));
connect(ui->pushButtonStart,SIGNAL(clicked()),this,SLOT(clickStartSlot()));
connect(ui->pushButtonEnd,SIGNAL(clicked()),this,SLOT(clickEndSlot()));
}
//到时间会更新显示
void Dialog::timeoutSlot()
{
count++;
if(count==4)
count=0;
QSize size(ui->labelImg->width(),ui->labelImg->height());
QPixmap img(list[count]);
img = img.scaled(size,Qt::KeepAspectRatioByExpanding);
ui->labelImg->setPixmap(img);
}
void Dialog::clickStartSlot()
{
//启动定时器
timer->start();
}
void Dialog::clickEndSlot()
{
//关闭定时器
timer->stop();
}
//上一张
void Dialog::clickPeriousSlot()
{
if(count==0)
count=4;
else
count--;
QSize size(ui->labelImg->width(),ui->labelImg->height());
QPixmap img(list[count]);
img = img.scaled(size,Qt::KeepAspectRatioByExpanding);
ui->labelImg->setPixmap(img);
}
//下一张
void Dialog::clickNextSlot()
{
if(count==4)
count=0;
else
count++;
QSize size(ui->labelImg->width(),ui->labelImg->height());
QPixmap img(list[count]);
img = img.scaled(size,Qt::KeepAspectRatioByExpanding);
ui->labelImg->setPixmap(img);
}
Dialog::~Dialog()
{
delete timer;
delete ui;
}