17、Qt学习笔记--FFMPEG Qt视频播放器之显示图像

一、介绍

1、论坛中有人说使用QLabel显示视频流会占用较多的CPU资源,使用QPainter直接画出来会节约资源,自己试了一下,发展没啥区别(只是在自己的笔记本上做对比,没在其他电脑上做对比)。

2、主要思路是,重写widget中的私有函数paintEvent,将要画出的图像在此函数中实现,然后用定时器connnect一个槽函数,在该槽函数中发送信号update。调用update会执行paintEvent函数。


二、工程

1、代码

//
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    qtimer = new QTimer(this);
    myvideo.open_video(0);
    connect(qtimer, SIGNAL(timeout()), this, SLOT(slotGetOneFrame()));
    qtimer->start(10);
}

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

void Widget::paintEvent(QPaintEvent *)
{
//    QPainter painter(this);
//    int x1 = ui->frame4video0->pos().x();
//    int y1 = ui->frame4video0->pos().y();
//    image0.fromImage(myvideo.readFrame());
//    image0.load("C:/Users/wse/Desktop/OpenGLDemo/robot.jpg");
//    painter.drawPixmap(x1, y1, ui->frame4video0->width(), ui->frame4video0->height(), image0);
    QPainter painter(this);
    painter.setBrush(Qt::white);
    painter.drawRect(0, 0, this->width(), this->height()); //先画成白色

    if (mImage.size().width() <= 0) return;

    ///将图像按比例缩放成和窗口一样大小
    QImage img = mImage.scaled(this->size(),Qt::KeepAspectRatio);

    int x = this->width() - img.width();
    int y = this->height() - img.height();

    x /= 2;
    y /= 2;

    painter.drawImage(QPoint(x,y),img); //画出图像
}

void Widget::slotGetOneFrame()
{
    mImage = myvideo.readFrame();
    update(); //调用update将执行 paintEvent函数
}
//

2、完整工程

博主修改过的工程(opencv)


致谢

1、FFmpeg+Qt实现摄像头(rtsp)实时显示

2、完整工程下载

3、博主修改过的工程(opencv)

猜你喜欢

转载自blog.csdn.net/qq_38880380/article/details/80969451