QT實時視訊播放介面設計
阿新 • • 發佈:2018-10-31
QT播放介面設計
今天寫了個QT的實時視訊播放介面,其實要寫一個播放介面非常容易,以下為程式碼
首先定義一個用於播放的控制元件:
* PlsyItem.h
#ifndef PLAYITEM_H
#define PLAYITEM_H
#include <QObject>
#include <QGraphicsItem>
#include <QImage>
class PlayItem : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
public:
explicit PlayItem(QObject *parent = nullptr);
PlayItem(const QImage &qimg);
~PlayItem();
void setQImage(const QImage &qimg);
};
#endif // PLAYITEM_H
- PlsyItem.cpp
#include "PlayItem.h"
PlayItem::PlayItem(QObject *parent) : QObject(parent)
{
}
PlayItem::PlayItem(const QImage &qimg)
{
this ->setPixmap(QPixmap::fromImage(qimg));
this->update();
}
PlayItem::~PlayItem()
{
}
void PlayItem::setQImage(const QImage &qimg)
{
this->setPixmap(QPixmap::fromImage(qimg));
this->update();
}
然後定義一個 QGraphicsView,用於顯示
* PlayWidget.h
#ifndef PLAYWIDGET_H
#define PLAYWIDGET_H
#include <QGraphicsView>
#include <QGraphicsScene>
#include <opencv2/core/core.hpp>
#include "PlayItem.h"
class PlayWidget : public QGraphicsView
{
Q_OBJECT
public:
PlayWidget();
public slots:
void getResult(const QImage &qimg);
private:
// QImage Mat2QImage(const cv::Mat &img);
void updateScene();
// event
void wheelEvent(QWheelEvent *event);
private:
PlayItem* m_play_item_ptr;
QGraphicsScene* m_img_scene_ptr;
cv::Mat m_img;
double m_zoom_factor;
};
#endif // PLAYWIDGET_H
- PlayWidget.cpp
#include "PlayWidget.h"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <QWheelEvent>
PlayWidget::PlayWidget()
{
m_img_scene_ptr = new QGraphicsScene();
this->setScene(m_img_scene_ptr);
m_play_item_ptr = new PlayItem();
m_img_scene_ptr->addItem(m_play_item_ptr);
double width_scale = double(this->width()) / double(1280);
double height_scale = double(this->height()) / double(720);
m_zoom_factor = width_scale < height_scale ? width_scale : height_scale;
this->updateScene();
}
void PlayWidget::getResult(const QImage &qimg)
{
m_play_item_ptr->setQImage(qimg);
}
void PlayWidget::updateScene()
{
QMatrix matrix;
matrix.scale(m_zoom_factor, m_zoom_factor);
this->setMatrix(matrix);
}
void PlayWidget::wheelEvent(QWheelEvent *event)
{
if(event->delta() > 0)
m_zoom_factor *= 1.15;
else
m_zoom_factor *= 0.9;
this->updateScene();
}
然後將PlayWidget類作為主視窗或者某個窗體的控制元件即可,當PlayWidget收到QImage,便可以顯示出來,而且可以縮放