QT 简易视频播放器版本1.1

news2024/12/23 14:10:36
  • 设计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();
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/708803.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

深入了解Promise机制并使用JS实现一个Promise(一)

前言 关于为什么会有Promise以及Promise的一些用法和基本机制可以参考之前的文章JS中的异步与Promise使用整体来说&#xff0c;Promise可以帮助我们很好的解决异步的问题&#xff0c;号称是异步的终极解决方案。在浏览器中Promise是使用C实现的&#xff0c;今天就使用js来实现…

JSP原理以及基本语法

1、JSP原理 什么是JSP&#xff1f; Java Server Pages&#xff1a;Java服务器页面&#xff0c;和Servlet一样是动态Web技术&#xff01; 和HTML的区别&#xff1f; HTML是静态页面。在JSP页面中可以嵌入Java代码&#xff0c;为用户提供动态的数据。 JSP 和 Servlet 的关系…

枚举一个进程中的所有线程

在 Win32 开发中&#xff0c;如果需要获取程序运行过程中的一些较为底层的信息&#xff0c;你可能需要使用到 Tool Helper 库。但我愿意称之它为 Win32 中的 “害群之马”。何解&#xff1f; Tool Helper 库在 16 位 Windows 时代就已经存在了&#xff0c;这个库主要用来提供一…

今天给我的Ubuntu服务器挂在了一个4T的硬盘却只能识别到2T,原来是因为这!涨知识了

前言 今天买的4T机械硬盘到了&#xff0c;准备给我的服务器加装上&#xff0c;用来作为Nextcloud的存储硬盘。把硬盘安装好后就迫不及待的进行挂载&#xff0c;挂载的操作倒是挺顺利的&#xff0c;但是无论怎么操作Ubuntu系统识别到的大小居然都是2T&#xff0c;最后没办法&am…

chatgpt赋能python:开方在Python中的用法

开方在Python中的用法 开方是数学中常见的一种运算&#xff0c;用于求一个数的平方根。在Python中&#xff0c;开方运算可以通过使用math模块中的sqrt函数来实现。本文将介绍开方运算的概念、Python中的应用以及一些常见问题的解决方法。 开方的概念 开方是指&#xff0c;对…

chatgpt赋能python:在Python中运行程序的方法介绍

在Python中运行程序的方法介绍 Python是一种广泛使用的编程语言&#xff0c;也是人工智能和数据科学领域的首选。在这篇SEO文章中&#xff0c;我们将介绍Python中运行程序的几种方法。 1. 在Python环境中运行程序 Python环境是一个Python解释器及其标准库的集合。为了在Pyth…

Redis7【⑥ Redis复制(replica)】

Redis复制 Redis 复制&#xff08;Replication&#xff09;是 Redis 的一项核心功能&#xff0c;用于将一个 Redis 数据库的所有数据复制到另一个 Redis 实例上。Redis 复制可以提高系统的可用性、可靠性和扩展性&#xff0c;使得在发生故障时可以快速地恢复数据。 Redis 复制…

【TiDB v7.1.0】资源管控调研及评测

作者&#xff1a; angryart 原文来源&#xff1a; https://tidb.net/blog/ad24240a 多租户是什么 有语云&#xff0c;食在广州&#xff0c;玩在杭州&#xff0c;死在柳州&#xff0c;广东人除了天上飞的飞机不吃&#xff0c;地上走的坦克不吃&#xff0c;其它的什么都吃&am…

Mybatis面试题--MyBatis一级缓存,二级缓存

Mybatis的一级、二级缓存用过吗&#xff1f; 一级缓存: 基于 PerpetualCache 的 HashMap 本地缓存&#xff0c;其存储作用域为 Session&#xff0c;当Session进行flush或close之后&#xff0c;该Session中的所有Cache就将清空&#xff0c;默认打开一级缓存 二级缓存 是基于n…

Python将多维列表「拉伸」为一维列表的10种方式

来源&#xff1a;投稿 作者&#xff1a;Fairy 编辑&#xff1a;学姐 在Python编程中&#xff0c;列表是一种常用的数据类型。当我们遇到了一个嵌套列表&#xff0c;如果想将它扁平化为一维列表&#xff0c;就可以使用下面10种方法之一来实现这个需求。 1. 使用两层循环遍历 l…

【记录】实践场景

Apache Doris 在京东搜索实时 OLAP 探索与实践 https://doris.apache.org/zh-CN/blog/JD_OLAP/ 通过对比开源的几款实时OLAP引擎&#xff0c;我们发现doris和clickhouse能够满足我们的需求&#xff0c;但是clickhouse的并发度太低是个潜在的风险&#xff0c;而且clickhouse的数…

已将该虚拟机配置为使用 64 位客户机操作系统。但是,无法执行 64 位操作。

错误提示&#xff1a; 一般只有下面几种方法 百度经验解决方法 http://jingyan.baidu.com/article/90bc8fc859b481f653640cac.html http://jingyan.baidu.com/article/25648fc1bfd4a29190fd0067.html 2.第二种方法 检测问题所在&#xff1a; 下载LeoMoon CPU-V 检查一下CP…

小程序本地生活

2023年7月1号 感觉就是视频要快点看不完 不然哪天接口又失效了 Page({/*** 页面的初始数据*/data: {// 存放轮播图的数据swiperList:[],// 存放九宫格的数据gridList:[]},/*** 生命周期函数--监听页面加载*/onLoad(options) {this.getSwiperList()this.getGridList()},// 获…

【GIS】阿里AI Earth选择内置地图

说明 aie.Map&#xff0c;构造一个地图组件Map对象&#xff0c;用于可视化渲染计算结果。坐标系固定为EPSG:4326。 阿里AI Earth中&#xff0c;坐标系默认为EPSG:4326 效果 import aie aie.Authenticate() aie.Initialize() my_province aie.FeatureCollection(China_Provin…

【Python】Python基础笔记

Python基础笔记 数据的输入和输出 print("数据") # 这是数据的输出 name input() # 这是数据的输入&#xff0c;并将输入的数据赋值给name。而且无论输入的何种类型的数据&#xff0c;最终的结果都是 字符串 类型的数据pint 输出不换行&#xff1a; # print 输出…

结合ace编辑器实现MapboxGL热力图样式在线配置

概述 MapboxGL热力图的配置参数并不多&#xff0c;但是有时候为了或得一个比较好用的热力图配置参数&#xff0c;我们不得不改代码再预览&#xff0c;显得尤为麻烦&#xff0c;为方便配置&#xff0c;实现实时预览&#xff0c;本文使用ace实现了一个热力图样式在线配置页面。 …

MSF之信息收集及漏洞利用

MSF之信息收集及漏洞利用 一、Metasploit简介二、Metasploit安装三、安装postgresql数据库四、KaIi-msfdb-Postgresql报错排查处理五、Metasploit-启动六、Metasploit-目录结构六、Metasploit-模块七、Metasploit-信息收集7.1、db_nmap/nmap7.2、Metasploit auxiliary7.2.1、端…

【STM32】步进电机及其驱动(ULN2003驱动28BYJ-48丨按键控制电机旋转)

本篇文章包含的内容 一、步进电机的结构和工作原理1.1 步进控制系统的组成1.2 步进电机简介1.3 步进电机的分类1.4 步进电机的工作原理1.4.1 单极性步进电机&#xff08;5线4相&#xff09;1.4.2 双极性步进电机&#xff08;4线2相&#xff09;1.4.3 细分器驱动原理 1.5 步进电…

hcia回顾复习

一、OSI七层参考模型 OSI/RM 开放式系统互联参考模型 由ISO ---- 国际标准化组织 — 1979提出 核心思想 分层 :上层协议再下层协议提供服务的基础上再提供增值服务。 应用层 — 提供各种应用服务.可以将抽象语言转换为编码 .应用程序 APP&#xff1a;通过人机交互提供&#xff…

Win10打字输入法不显示输入框怎么办?

Win10的打字输入法是我们日常计算机使用中必不可少的工具之一&#xff0c;然而&#xff0c;有时候在使用过程中可能会遇到打字输入法不显示输入框的问题&#xff0c;这给我们的输入和操作带来了很大的困扰&#xff0c;如果您也遇到了这个问题&#xff0c;不要担心&#xff0c;以…