- 设计Qt界面
- 实现播放、暂停、停止、下一集、上一集、快进、后退、倍速播放、进度调节,音量调节、视频播放列表等功能
先上演示效果:
ui界面设计
videoplayer.h
#ifndef VIDEOPLAYER_H
#define VIDEOPLAYER_H
#pragma execution_character_set("utf-8")
#include <QDialog>
#include <QMainWindow>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QVideoWidget>
#include <QGraphicsVideoItem>
#include <QFileDialog>
#include <QGraphicsScene>
#include <QMessageBox>
#include <QListWidgetItem>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class VideoPlayer; }
QT_END_NAMESPACE
class VideoPlayer : public QMainWindow
{
Q_OBJECT
public:
public:
VideoPlayer(QWidget *parent = nullptr);
~VideoPlayer();
private:
Ui::VideoPlayer *ui;
private:
QMediaPlayer *player;
QGraphicsVideoItem *videoItem;
QString durationtime,positiontime;
QTimer * timer;
int maxValue = 100;//设置进度条的最大值
qint64 dur;
qint64 pos;
bool isLoop = false;
QMediaPlaylist *mediaPlaylist;
QString openFilePath;
int curIndex = -1;
int OriginWidth;
QList<QString> videoList;
private slots:
//初始化窗口
void initWidget();
//媒体初始化
void mediaPlayerInit();
//自定义槽函数
// void onStateChanged(QMediaPlayer::State state);
// 视频总长度
void onDurationChanged(qint64 duration);
// 当前位置
void onPositionChanged(qint64 position);
void on_timeout();
void on_TimeSlider_sliderPressed();
void on_TimeSlider_sliderMoved(int position);
void on_TimeSlider_sliderReleased();
//点击进度条触发的槽函数
void sliderClicked();
void volumeSliderClicked();
void MediaPlayClicked();
//循环和顺序播放图标的label点击
void labelClicked();
void MediaFastForwardClicked();
void MediaDrawBackClicked();
void volumeClicked();
void listLabelClicked();
void openVideoClicked();
void on_volumeSlider_sliderMoved(int position);
void seekForward();
void seekBackward();
void on_comboBox_speed_currentIndexChanged(int index);
void setPlaySpeed(double speed); //设置播放速度
void getData(QList<QString> videoList,int curIndex);
void preLabelClicked();//上一集
void nextLabelClicked();//下一集
void playVideo(QString openFilePath);//播放视频
signals:
int sendCurIndex(int);//发送curIndex
};
#endif // VIDEOPLAYER_H
videoplayer.cpp
#include "videoplayer.h"
#include "ui_videoplayer.h"
#include <QTime>
#include <QDebug>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "Mylabel.h"
VideoPlayer::VideoPlayer(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::VideoPlayer)
{
ui->setupUi(this);
//固定窗口尺寸(以用户设计窗口为准)
setFixedSize(width(),height());
initWidget(); // 初始化窗口
mediaPlayerInit(); // 媒体播放初始化
//定时器,用于获取视频当前播放时间,毫秒值
this->timer = new QTimer(this);//定时器
connect(timer,&QTimer::timeout,this,&VideoPlayer::on_timeout);
/* 媒体连接信号槽 */
connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(onPositionChanged(qint64)));
//connect(player,SIGNAL(stateChanged(QMediaPlayer::State)),this,SLOT(onStateChanged(QMediaPlayer::State)));
connect(player, SIGNAL(durationChanged(qint64)), this, SLOT(onDurationChanged(qint64)));//视频持续时间,毫秒值 mediaPlayer->duration()可以直接获取
/* 视频进度条和音量调节*/
//自定义的信号costomSliderClicked()
connect(ui->TimeSlider,SIGNAL(costomSliderClicked()),this,SLOT(sliderClicked()));
connect(ui->volumeSlider,SIGNAL(costomSliderClicked()),this,SLOT(volumeSliderClicked()));
/* 图标连接信号槽 自定义的信号clicked()*/
connect(ui->openVideoLabel,SIGNAL(clicked()),this,SLOT(openVideoClicked()));//打开文件
connect(ui->playMode,SIGNAL(clicked()),this,SLOT(labelClicked()));//循环播放
connect(ui->preLabel,SIGNAL(clicked()),this,SLOT(preLabelClicked()));//上一集
connect(ui->nextLabel,SIGNAL(clicked()),this,SLOT(nextLabelClicked()));//下一集
connect(ui->accelerateLabel,SIGNAL(clicked()),this,SLOT(MediaFastForwardClicked())); //快进
connect(ui->moderateLabel,SIGNAL(clicked()),this,SLOT(MediaDrawBackClicked()));//后退
connect(ui->playVideoLabel,SIGNAL(clicked()),this,SLOT(MediaPlayClicked()));//播放/暂停
connect(ui->volumeLabel,SIGNAL(clicked()),this,SLOT(volumeClicked()));//小喇叭设置静音/声音
connect(ui->listLabel,SIGNAL(clicked()),this,SLOT(listLabelClicked()));//展开视频列表
//视频播放列表widget向主界面发送信号,主界面与其连接,获取数据
connect(ui->widget,SIGNAL(sendData(QList<QString>,int)),this,SLOT(getData(QList<QString>,int)));
}
VideoPlayer::~VideoPlayer()
{
delete player;
delete mediaPlaylist;
delete ui;
}
//
//初始化窗口
void VideoPlayer::initWidget(){
/* 视频窗口 */
// videoWidget = new QVideoWidget();
// videoWidget->setStyleSheet("border-image: none;" "background: transparent;""border:none");
// videoWidget->setMinimumSize(500, 480); // 视频窗口大小
OriginWidth = width();
setWindowOpacity(0.98);
QPalette pal = palette();
pal.setColor(QPalette::Background, QColor( 230, 230, 250));
setPalette(pal);
//this->setStyleSheet("background-color:rgba(240,255,255,0.5)");
QGraphicsScene * scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
ui->graphicsView->setBackgroundBrush(QColor(0, 0, 0)); // 设置黑色背景
videoItem = new QGraphicsVideoItem;
videoItem->setSize(QSize(ui->graphicsView->width(),ui->graphicsView->height()));
videoItem->setFlags(QGraphicsItem::ItemIsMovable|
QGraphicsPathItem::ItemIsSelectable|
QGraphicsItem::ItemIsFocusable);
scene->addItem(videoItem);
ui->graphicsView->setStyleSheet("border-image: none;" "background: transparent;""border:none");
ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 隐藏垂直滚动条
ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 隐藏水平滚动条
//UI控件的样式设计
ui->volumeSlider->setStyleSheet(
"QSlider::groove:horizontal{"
"border:1px solid skyblue;"
"background-color:skyblue;"
"height:10px;"
"border-radius:5px;"
"}"
"QSlider::handle:horizontal{"
"background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,stop:0.7 white,stop:0.8 rgb(140,212,255));"
"width:20px;"
"border-radius:10px;"
"margin-top:-5px;"
"margin-bottom:-5px;"
"}"
"#volumeSlider:sub-page:horizontal{"
"background:green;"
"margin:5px;"
"border-radius:5px;}"
);
ui->TimeSlider->setStyleSheet(
"QSlider::groove:horizontal{"
"border:1px solid skyblue;"
"background-color:skyblue;"
"height:10px;"
"border-radius:5px;"
"}"
"QSlider::handle:horizontal{"
"background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,stop:0.7 white,stop:0.8 rgb(140,212,255));"
"width:20px;"
"border-radius:10px;"
"margin-top:-5px;"
"margin-bottom:-5px;"
"}"
"#TimeSlider:sub-page:horizontal{"
"background:green;"
"margin:5px;"
"border-radius:5px;}"
);
//打开视频图标
QString openFilePath = ":/images/openFile.png";//图标位置自行调整
QIcon openFileLabelIcon = QIcon(openFilePath);
QPixmap m_openFilelPic = openFileLabelIcon.pixmap(openFileLabelIcon.actualSize(QSize(ui->openVideoLabel->width(),
ui->openVideoLabel->height())));//size自行调整
ui->openVideoLabel->setPixmap(m_openFilelPic);
//设置循环/顺序播放图标
QString filePath = ":/images/seqPlay.png";//图标位置自行调整
QIcon icon = QIcon(filePath);
QPixmap m_pic = icon.pixmap(icon.actualSize(QSize(ui->playMode->width(), ui->playMode->height())));//size自行调整
ui->playMode->setPixmap(m_pic);
//快进播放图标
QString accFilePath = ":/images/accelerate.png";//图标位置自行调整
QIcon accIcon = QIcon(accFilePath);
QPixmap m_accPic = accIcon.pixmap(accIcon.actualSize(QSize(ui->accelerateLabel->width(),
ui->accelerateLabel->height())));//size自行调整
ui->accelerateLabel->setPixmap(m_accPic);
//小喇叭图标
QString volumeFilePath = ":/images/volume.png";//图标位置自行调整
QIcon volumeIcon = QIcon(volumeFilePath);
QPixmap m_volumePic = volumeIcon.pixmap(volumeIcon.actualSize(QSize(ui->volumeLabel->width(),
ui->volumeLabel->height())));//size自行调整
ui->volumeLabel->setPixmap(m_volumePic);
//后退播放图标
QString modFilePath = ":/images/moderate.png";//图标位置自行调整
QIcon modIcon = QIcon(modFilePath);
QPixmap m_modPic = modIcon.pixmap(modIcon.actualSize(QSize(ui->moderateLabel->width(),
ui->moderateLabel->height())));//size自行调整
ui->moderateLabel->setPixmap(m_modPic);
//暂停播放图标
QString playFilePath = ":/images/pause1.png";//图标位置自行调整
QIcon playIcon = QIcon(playFilePath);
QPixmap m_playPic = playIcon.pixmap(playIcon.actualSize(QSize(ui->playVideoLabel->width(),
ui->playVideoLabel->height())));//size自行调整
ui->playVideoLabel->setPixmap(m_playPic);
//设置上一集图标
QString preImagePath = ":/images/pre.png";//图标位置自行调整
QIcon preIcon = QIcon(preImagePath);
QPixmap m_prePic = preIcon.pixmap(preIcon.actualSize(QSize(ui->preLabel->width(),
ui->preLabel->height())));//size自行调整
ui->preLabel->setPixmap(m_prePic);
//设置下一集图标
QString nextImagePath = ":/images/next.png";//图标位置自行调整
QIcon nextIcon = QIcon(nextImagePath);
QPixmap m_nextPic = nextIcon.pixmap(preIcon.actualSize(QSize(ui->nextLabel->width(),
ui->nextLabel->height())));//size自行调整
ui->nextLabel->setPixmap(m_nextPic);
//视频列表图标
QString listLabelFilePath = ":/images/videoList.png";//图标位置自行调整
QIcon listLabelIcon = QIcon(listLabelFilePath);
QPixmap m_listLabelPic = listLabelIcon.pixmap(listLabelIcon.actualSize(QSize(ui->listLabel->width(),
ui->listLabel->height())));//size自行调整
ui->listLabel->setPixmap(m_listLabelPic);
//初始化不展示视频列表
ui->widget->setVisible(false);
setFixedSize(ui->graphicsView->width(),height());
//设置状态栏的背景颜色
ui->statusbar->setStyleSheet("background-color:#F0F8FF;border: transparent;");
//设置倍速播放样式
ui->comboBox_speed->setStyleSheet("background-color:#FFFAFA;"
"border-radius: 7px;"
"border: 1px solid gray;");
}
//媒体初始化
void VideoPlayer::mediaPlayerInit()
{
//视频播放器初始化参数
player = new QMediaPlayer(this);
//player->setNotifyInterval(2000);
mediaPlaylist = new QMediaPlaylist(this); // 播放列表
mediaPlaylist->clear();
player->setPlaylist(mediaPlaylist);
//player->setVideoOutput(videoWidget); // 设置视频输出窗口
player->setVideoOutput(videoItem);
//mediaPlaylist->setPlaybackMode(QMediaPlaylist::Loop); // 设置播放模式,Loop 是列循环
//player->setVolume(50); // 设置默认软件音量为 50%
ui->comboBox_speed->setCurrentIndex(2);
int index = ui->comboBox_speed->currentIndex();//获得索引
qDebug()<<index<<endl;
}
//
void VideoPlayer::MediaPlayClicked(){
int state = player->state();//获取播放器的状态
if(state == QMediaPlayer::PausedState){//暂停
player->play();
QIcon playIcon = QIcon(":/images/pause1.png");
QPixmap m_playPic = playIcon.pixmap(playIcon.actualSize(QSize(ui->playVideoLabel->width(),
ui->playVideoLabel->height())));//size自行调整
ui->playVideoLabel->setPixmap(m_playPic);
}
else if(state == QMediaPlayer::PlayingState){//播放中
player->pause();
QIcon playIcon = QIcon(":/images/pause.png");
QPixmap m_playPic = playIcon.pixmap(playIcon.actualSize(QSize(ui->playVideoLabel->width(),
ui->playVideoLabel->height())));//size自行调整
ui->playVideoLabel->setPixmap(m_playPic);
}
}
void VideoPlayer::volumeClicked(){
bool mte = player->isMuted();
player->setMuted(!mte);
if(mte){
QIcon volumeIcon = QIcon(":/images/volume.png");
QPixmap m_volumePic = volumeIcon.pixmap(volumeIcon.actualSize(QSize(ui->volumeLabel->width(),
ui->volumeLabel->height())));//size自行调整
ui->volumeLabel->setPixmap(m_volumePic);
}else{
QIcon volumeIcon = QIcon(":/images/mute.png");
QPixmap m_volumePic = volumeIcon.pixmap(volumeIcon.actualSize(QSize(ui->volumeLabel->width(),
ui->volumeLabel->height())));//size自行调整
ui->volumeLabel->setPixmap(m_volumePic);
}
}
void VideoPlayer::listLabelClicked(){
qDebug()<<"切换展示视频播放列表"<<endl;
// qDebug()<<ui->graphicsView->width();
// qDebug()<<OriginWidth<<endl;
if(ui->widget->isVisible()){
ui->widget->setVisible(false);
setFixedSize(ui->graphicsView->width(),height());
}else{
ui->widget->setVisible(true);
setFixedSize(OriginWidth,height());
}
}
void VideoPlayer::openVideoClicked(){
QString strCurrentPath = QDir::homePath();//获取系统当前目录
QString strDlgTitle = "请选择视频文件";//打开文件对话框标题
QString strFilter = "MP4 Files(*.mp4);;WMV(*.wmv);;AVI(*.avi);;All Files(*.*)";//打开视频文件过滤器
QString strAllFiles = QFileDialog::getOpenFileName(this,strDlgTitle,strCurrentPath,strFilter);
//QMessageBox::information(this,"提示",strAllFiles,QMessageBox::Yes|QMessageBox::No);
if(strAllFiles.isEmpty()){
QMessageBox::information(this,"错误","打开视频文件失败,请重新检查",QMessageBox::Yes|QMessageBox::No);
//QMessageBox::critical(this,"错误","打开视频文件失败,请重新检查",QMessageBox::Yes);
return;
}
QFileInfo FileInfo(strAllFiles);//获取文件信息
playVideo(strAllFiles);//播放视频
}
//
//循环和顺序播放图标的label点击
void VideoPlayer::labelClicked(){
QString filePath;
if(!isLoop){
filePath = ":/images/loopPlay.png";//图标位置自行调整
isLoop = true;
//mediaPlaylist->setPlaybackMode(QMediaPlaylist::Loop);// 通过设置 播放列表循环 实现循环播放
}else{
filePath = ":/images/seqPlay.png";//图标位置自行调整
isLoop = false;
//mediaPlaylist->setPlaybackMode(QMediaPlaylist::Sequential);// 通过设置 播放列表循环 实现循环播放
}
QIcon icon = QIcon(filePath);
QPixmap m_pic = icon.pixmap(icon.actualSize(QSize(ui->playMode->width(), ui->playMode->height())));//size自行调整
ui->playMode->setPixmap(m_pic);
}
void VideoPlayer::MediaFastForwardClicked(){
seekForward();
QTime dieTime = QTime::currentTime().addMSecs(1000);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
player->play();
}
void VideoPlayer::MediaDrawBackClicked(){
seekBackward();
QTime dieTime = QTime::currentTime().addMSecs(1000);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
player->play();
}
void VideoPlayer::seekForward()
{
qDebug()<<"设置每次点击快进的距离";
player->pause();
ui->TimeSlider->setValue(ui->TimeSlider->value() + ui->TimeSlider->width()*0.1);
qDebug()<<ui->TimeSlider->value();
player->setPosition(ui->TimeSlider->value());
}
void VideoPlayer::seekBackward()
{
qDebug()<<"设置每次点击后退的距离";
player->pause();
ui->TimeSlider->setValue(ui->TimeSlider->value() - ui->TimeSlider->width()*0.1);
player->setPosition(ui->TimeSlider->value());
}
//播放器进度条范围
void VideoPlayer::onDurationChanged(qint64 duration){
if(duration > 0){
ui->TimeSlider->setEnabled(true);
//设置进度条范围
ui->TimeSlider->setRange(0,duration);
}
}
//播放器进度条位置
void VideoPlayer::onPositionChanged(qint64 position){
ui->TimeSlider->setValue(position);
}
//
//slider点击事件发生后,改变视频的进度
void VideoPlayer::sliderClicked(){
player->setPosition(ui->TimeSlider->value());
int state = player->state();//获取播放器的状态
if(state == QMediaPlayer::StoppedState){
player->play();
QString playFilePath = ":/images/pause1.png";
QIcon playIcon = QIcon(playFilePath);
QPixmap m_playPic = playIcon.pixmap(playIcon.actualSize(QSize(ui->playVideoLabel->width(),
ui->playVideoLabel->height())));//size自行调整
ui->playVideoLabel->setPixmap(m_playPic);
}
}
//更新播放时间轴和时间戳
void VideoPlayer::on_timeout()
{
dur = player->duration();//获取到总时长2
pos = player->position();//获取当前的播放位置
ui->showTime->setText(QTime::fromMSecsSinceStartOfDay(pos).toString("hh:mm:ss")+"/"+QTime::fromMSecsSinceStartOfDay(dur).toString("hh:mm:ss"));
/* 播放结束 根据设置的播放模式:循环播放 和 顺序播放 来实现循环/顺序模式的播放 */
if(pos == dur && dur!=0){
//qDebug()<<"dur"<<dur;
if(isLoop){
qDebug()<<"结束了...";
player->setPosition(0);
player->play();
QString playFilePath = ":/images/pause1.png";
QIcon playIcon = QIcon(playFilePath);
QPixmap m_playPic = playIcon.pixmap(playIcon.actualSize(QSize(ui->playVideoLabel->width(),
ui->playVideoLabel->height())));//size自行调整
ui->playVideoLabel->setPixmap(m_playPic);
} else{
QString playFilePath = ":/images/pause.png";//图标位置自行调整
QIcon playIcon = QIcon(playFilePath);
QPixmap m_playPic = playIcon.pixmap(playIcon.actualSize(QSize(ui->playVideoLabel->width(),
ui->playVideoLabel->height())));//size自行调整
ui->playVideoLabel->setPixmap(m_playPic);
}
}
}
//时间轴: 按下鼠标左键
void VideoPlayer::on_TimeSlider_sliderPressed()
{
// timer->stop();
// qDebug()<<ui->TimeSlider->sliderPosition();
// player->pause();
// player->setPosition(ui->TimeSlider->sliderPosition());
//player->setPosition(position*player->duration()/maxValue);
qDebug()<<"on_TimeSlider_sliderPressed";
int currentValue=ui->TimeSlider->value();
qDebug()<<"currentValue"<<currentValue;
}
// 时间轴:鼠标移动
void VideoPlayer::on_TimeSlider_sliderMoved(int position)
{
player->pause();
//根据滑块的位置设置播放视频的位置
player->setPosition(position); //跳转到position 时间点位置
//timer->stop();
//player->setPosition(ui->TimeSlider->value()*player->duration()/maxValue);
}
//时间轴: 鼠标离开
void VideoPlayer::on_TimeSlider_sliderReleased()
{
player->play();
// timer->start();
}
//设置volumeSlider
void VideoPlayer::on_volumeSlider_sliderMoved(int position)
{
// qDebug()<<"position:"<<position;
player->setVolume(position);
}
//slider点击事件发生后,改变视频的进度
void VideoPlayer::volumeSliderClicked(){
player->setVolume(ui->volumeSlider->value());
qDebug()<<"ui->volumeSlider->value():"<<ui->volumeSlider->value();
// player->setVolume(ui->volumeSlider->value());
// ui->volumeSlider->setValue(ui->volumeSlider->value());
}
void VideoPlayer::setPlaySpeed(double speed)
{
player->setPlaybackRate(speed); //设置播放速度
}
void VideoPlayer::on_comboBox_speed_currentIndexChanged(int index)
{
player->pause();
if(index == 0) this->setPlaySpeed(0.5);
else if(index == 1) this->setPlaySpeed(0.75);
else if(index == 2) this->setPlaySpeed(1.0);
else if(index == 3) this->setPlaySpeed(1.25);
else if(index == 4) this->setPlaySpeed(1.5);
else if(index == 5) this->setPlaySpeed(2.0);
player->play();
}
void VideoPlayer::playVideo(QString openFilePath){
player->setMedia(QUrl::fromLocalFile(openFilePath));
qDebug()<<"播放视频"<<endl;
QString playFilePath = ":/images/pause1.png";
QIcon playIcon = QIcon(playFilePath);
QPixmap m_playPic = playIcon.pixmap(playIcon.actualSize(QSize(ui->playVideoLabel->width(),
ui->playVideoLabel->height())));//size自行调整
ui->playVideoLabel->setPixmap(m_playPic);
player->play();
//启用volumeSlider并设置范围
//ui->volumeSlider->setRange(0,maxValue);
ui->volumeSlider->setValue(player->volume()/2);
player->setVolume(player->volume()/2);
//启用slider并设置范围
ui->TimeSlider->setEnabled(true);
//ui->TimeSlider->setRange(0,maxValue);
timer = new QTimer();
timer->setInterval(100);//如果想看起来流畅些,可以把时间间隔调小,如100ms
timer->start();
//将timer连接至onTimerOut槽函数
connect(timer, SIGNAL(timeout()), this, SLOT(on_timeout()));
}
void VideoPlayer::getData(QList<QString> videoList,int curIndex)
{
this->videoList = videoList;
this->curIndex = curIndex;
this->openFilePath = videoList[curIndex];
playVideo(this->openFilePath);
}
//上一集
void VideoPlayer::preLabelClicked(){
if(this->curIndex>0){
this->openFilePath = this->videoList[this->curIndex-1];
this->curIndex-=1;
qDebug()<<"执行 上一集 操作" << "第" <<this->curIndex <<"集"<<endl;
playVideo(this->openFilePath);//播放视频
connect(this,SIGNAL(sendCurIndex(int)),ui->widget,SLOT(getCurIndex(int)));//主界面向视频列表发送信号,与其建立连接
emit sendCurIndex(this->curIndex);
}
}
//下一集
void VideoPlayer::nextLabelClicked(){
if(this->curIndex<this->videoList.length()-1){
this->openFilePath = this->videoList[this->curIndex+1];
this->curIndex+=1;
qDebug()<<"执行 下一集 操作"<< "第" <<this->curIndex <<"集"<<endl;
playVideo(this->openFilePath);//播放视频
connect(this,SIGNAL(sendCurIndex(int)),ui->widget,SLOT(getCurIndex(int)));//主界面向视频列表发送信号,与其建立连接
emit sendCurIndex(this->curIndex);
}
}
videolist.h
#ifndef VIDEOLIST_H
#define VIDEOLIST_H
#include <QWidget>
#include <QButtonGroup>
#include <QListWidgetItem>
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include <QtCore>
namespace Ui {
class videoList;
}
class videoList : public QWidget
{
Q_OBJECT
public:
explicit videoList(QWidget *parent = nullptr);
~videoList();
private:
void onRadioButtonClicked();
void onItemClicked(QListWidgetItem* item);
void onItemDoubleClicked(QListWidgetItem* item);
private slots:
void onBtnAddClicked();
void onBtnDeleteClicked();
void on_videoListWidget_itemDoubleClicked(QListWidgetItem *item);
void getCurIndex(int curIndex);
signals:
void sendData(QList<QString>,int);
private:
Ui::videoList *ui;
QButtonGroup* mBtnGroup;
QList<QString> fileAllList;
QList<QString> fileNameAllList;
QString openFilePath;
bool strOmit = false;
};
#endif // VIDEOLIST_H
videolist.cpp
#include "videolist.h"
#include "ui_videolist.h"
#include <QRandomGenerator>
QStringList iconStringList = {
":/images/apple.png",
":/images/banana.png",
":/images/orange.png",
":/images/peach.png",
":/images/strawberry.png",
};
videoList::videoList(QWidget *parent) :
QWidget(parent),
ui(new Ui::videoList)
{
ui->setupUi(this);
// ui->videoListWidget->setFrameShape(QListWidget::NoFrame);
//设置显示模式
mBtnGroup = new QButtonGroup(this);
mBtnGroup->addButton(ui->rb_ListMode,0);
mBtnGroup->addButton(ui->rb_IconMode,1);
connect(ui->rb_ListMode,&QRadioButton::clicked,this,&videoList::onRadioButtonClicked);
connect(ui->rb_IconMode,&QRadioButton::clicked,this,&videoList::onRadioButtonClicked);
ui->rb_ListMode->setChecked(true);
ui->videoListWidget->setViewMode(QListView::ListMode);
//设置按钮的样式
ui->btn_Add->setDefault(1);//显示默认选中状态
ui->btn_Add->setStyleSheet("background-color:#FFDAB9;border-radius: 4px;border:1px solid gray");
ui->btn_Delete->setStyleSheet("background-color:#FFFACD;border-radius: 4px;border:1px solid gray");
//设置radioBtn样式
ui->rb_ListMode->setStyleSheet("QRadioButton::indicator{width: 20px;height: 20px;image: url(:/images/select.png);}"
"QRadioButton::indicator::checked{image: url(:/images/select.png);}"
"QRadioButton::indicator::unchecked{image: url(:/images/noSelect.png);}");
ui->rb_IconMode->setStyleSheet("QRadioButton::indicator{width: 20px;height: 20px;image: url(:/images/radioCircleLight.png);}"
"QRadioButton::indicator::checked{image: url(:/images/radioCircleLight.png);}"
"QRadioButton::indicator::unchecked{image: url(:/images/radioCircleClose.png);}");
//单击和双击信号槽
connect(ui->videoListWidget,&QListWidget::itemClicked,this,&videoList::onItemClicked);
connect(ui->videoListWidget,&QListWidget::itemDoubleClicked,this,&videoList::onItemDoubleClicked);
//add/delete
connect(ui->btn_Add,&QPushButton::clicked,this,&videoList::onBtnAddClicked);
connect(ui->btn_Delete,&QPushButton::clicked,this,&videoList::onBtnDeleteClicked);
//不显示行向滚动条,子项文本过长自动显示...
ui->videoListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui->videoListWidget->setStyleSheet("QScrollBar{width:10px;background:#0A1626;}");
QPalette pal = palette();
pal.setColor(QPalette::Background, QColor(248, 248, 255));
this->setPalette(pal);
this->show();
this->setAutoFillBackground(true);
//设置背景颜色
ui->videoListWidget->setStyleSheet("background-color:#FFFFFA;"
"border-radius: 7px;"
"border:1px solid gray;"); //transparent
}
videoList::~videoList()
{
delete ui;
}
void videoList::onRadioButtonClicked()
{
int checkedId = mBtnGroup->checkedId();
if(checkedId == 0){
//列表模式
ui->videoListWidget->setViewMode(QListView::ListMode);
}else if(checkedId == 1){
//图标模式
ui->videoListWidget->setViewMode(QListView::IconMode); //设置为自适应
ui->videoListWidget->setResizeMode(QListView::Adjust); //设置为自适应
ui->videoListWidget->setMovement(QListView::Static); //设置为不可拖动
ui->videoListWidget->setUniformItemSizes(true);
//ui->videoListWidget->setGridSize(QSize(40, 40));
ui->videoListWidget->setWordWrap(true);
//超出文本不显示省略号
// ui->videoListWidget->setTextElideMode(Qt::ElideNone);
}
}
//单击信号槽的时候获取文本
void videoList::onItemClicked(QListWidgetItem *item)
{
//ui->selectVideoFile->setText(item->text());
QString mStr = item->text();
ui->SelectVideoFile->setText(mStr);
QFontMetrics fontMetrics(ui->SelectVideoFile->font());
int fontSize = fontMetrics.width(mStr);
if (fontSize > ui->SelectVideoFile->width()) {
//省略左边的内容(Qt::ElideLeft) 省略中间的内容(Qt::ElideMiddle) 省略中间的内容(Qt::ElideRight)
ui->SelectVideoFile->setText(fontMetrics.elidedText(mStr, Qt::ElideMiddle, ui->SelectVideoFile->width()));
ui->SelectVideoFile->setToolTip(mStr);
} else {
ui->SelectVideoFile->setText(mStr);
ui->SelectVideoFile->setToolTip("");
}
}
//双击信号槽的时候变成可编辑的状态
void videoList::onItemDoubleClicked(QListWidgetItem *item)
{
item->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled);
}
//添加VideoItem
void videoList::onBtnAddClicked()
{
int iconIndex = QRandomGenerator::global()->generate()%5;//获取0-4的随机数
QIcon icon(iconStringList[iconIndex]);
QString strCurrentPath = QDir::homePath();//获取系统当前目录
QString strDlgTitle = "请选择视频文件";//打开文件对话框标题
QString strFilter = "MP4 Files(*.mp4);;WMV(*.wmv);;AVI(*.avi);;All Files(*.*)";//打开视频文件过滤器
QList<QString> fileList = QFileDialog::getOpenFileNames(this, strDlgTitle, strCurrentPath, strFilter);
for (int i= 0;i<fileList.length();i++) {
if(fileAllList.indexOf(fileList[i]) == -1){
fileAllList.append(fileList[i]);
QList<QString> fileNameList = fileList[i].split(".mp4")[0].split("/");
qDebug()<<fileNameList[fileNameList.length()-1];
QString text = fileNameList[fileNameList.length()-1] + ".mp4";//显示文件名字
QListWidgetItem* item = new QListWidgetItem(icon,text);
//ui->videoListWidget->addItem(item);
/************************ Qt QListWidget项文本过长显示处理 ************************/
//根据长度判断是否设置ToolTip
QFontMetrics fontMetrics(item->font());
if (ui->videoListWidget->width() < fontMetrics.width(text)){
item->setToolTip(text);
text =fontMetrics.elidedText(text, Qt::ElideMiddle, ui->SelectVideoFile->width());
}
item->setText(text);
item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
ui->videoListWidget->setIconSize(QSize(30, 30));
ui->videoListWidget->addItem(item);
// int currentRow = fileAllList.length() - ui->videoListWidget->currentRow();
// qDebug()<<ui->videoListWidget->currentRow();
// qDebug()<<currentRow;
// ui->videoListWidget->insertItem(currentRow,item);
}
}
qDebug()<<"fileList:"<<fileList;//打印视频文件列表
qDebug()<<"fileAllList:"<<fileAllList;//打印视频文件列表
}
//删除VideoItem
void videoList::onBtnDeleteClicked()
{
int row = ui->videoListWidget->currentRow();
qDebug()<<"删除第几行:"<<row;
QListWidgetItem *item = ui->videoListWidget->takeItem(row);
delete item;
ui->SelectVideoFile->setText("");
fileAllList.removeAt(row);
qDebug()<<"fileAllList:"<<fileAllList;//打印视频文件列表
}
void videoList::on_videoListWidget_itemDoubleClicked(QListWidgetItem *item)
{
//qDebug()<<"heheda";
int row = ui->videoListWidget->currentRow();
//qDebug()<<"选中第几行:"<<row;
//openFilePath = fileAllList[row];
//qDebug()<<openFilePath<<endl;
emit sendData(fileAllList,row);
}
void videoList::getCurIndex(int curIndex)
{
ui->videoListWidget->setCurrentRow(curIndex);
}
自定义:
customerlabel.h
#ifndef CUSTOMSLIDER_H
#define CUSTOMSLIDER_H
#include <QSlider>
#include <QMouseEvent>
#include <QCoreApplication>
class CustomSlider : public QSlider
{
Q_OBJECT
public:
CustomSlider(QWidget *parent = 0) : QSlider(parent)
{
}
protected:
void mousePressEvent(QMouseEvent *ev);//重写QSlider的mousePressEvent事件
signals:
void costomSliderClicked();//自定义的鼠标单击信号,用于捕获并处理
};
#endif // CUSTOMSLIDER_H
customerlabel.cpp
#include "customslider.h"
void CustomSlider::mousePressEvent(QMouseEvent *ev)
{
//注意应先调用父类的鼠标点击处理事件,这样可以不影响拖动的情况
QSlider::mousePressEvent(ev);
//获取鼠标的位置,这里并不能直接从ev中取值(因为如果是拖动的话,鼠标开始点击的位置没有意义了)
double pos = ev->pos().x() / (double)width();
//让进度条直接蹦过来
setValue(pos * (maximum() - minimum()) + minimum());
//发送自定义的鼠标单击信号
emit costomSliderClicked();
}
mylabel.h
#ifndef MYLABEL_H
#define MYLABEL_H
#include<QLabel>
#include<QString>
#include<QWidget>
#include<QMainWindow>
#include"QMessageBox"
class Mylabel:public QLabel
{
Q_OBJECT
public:
// Mylabel(const QString &text,QWidget *parent=0);
// ~Mylabel(){}
Mylabel(QWidget *parent = 0) : QLabel(parent)
{
}
signals:
void clicked();
//public slots:
// void slotClicked();
protected:
void mousePressEvent(QMouseEvent* event);
};
#endif // MYLABEL_H
mylabel.cpp
#include<QLabel>
#include"mylabel.h"
#include"videoplayer.h"
//Mylabel::Mylabel(const QString & text,QWidget* parent)
// :QLabel(parent)
//{
// this->setText(text);
// connect(this, SIGNAL(clicked()), this, SLOT(slotClicked()));
//}
//void Mylabel::slotClicked()
//{
// QMessageBox::information(NULL, QString::fromLocal8Bit("单击"),
// QString::fromLocal8Bit("马衍硕是不是很帅?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
//}
void Mylabel::mousePressEvent(QMouseEvent* event)
{
emit clicked();
}
main.cpp
#include "videoplayer.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
VideoPlayer w;
w.show();
return a.exec();
}