重写Qlabel类为ZoomableLabel
#pragma once
#include <QLabel>
#include <QPainter>
#include <QWheelEvent>
#include <QMouseEvent>
#include <QPixmap>
class ZoomableLabel : public QLabel {
Q_OBJECT
public:
QPixmap originalPixmap;
double zoomValue;
int xMove;
int yMove;
QPoint oldPos;
bool pressed;
explicit ZoomableLabel(QWidget *parent = nullptr)
: QLabel(parent),
zoomValue(1), xMove(0), yMove(0), pressed(false) {}
void setPixmap(const QPixmap &pixmap) {
zoomValue = qMin((float)this->width() / pixmap.width(), (float)this->height() / pixmap.height());
originalPixmap = pixmap;
update();
}
protected:
void wheelEvent(QWheelEvent *event) override
{
QPoint numDegrees = event->angleDelta() / 8;
if (!numDegrees.isNull())
{
if (numDegrees.y() > 0)
{
zoomIn();
}
else if (numDegrees.y() < 0)
{
zoomOut();
}
update();
}
}
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton)
{
oldPos = event->pos();
pressed = true;
}
else if (event->button() == Qt::RightButton)
{
xMove = 0;
yMove = 0;
zoomValue = qMin((float)this->width() / originalPixmap.width(), (float)this->height() / originalPixmap.height());
update();
}
}
void mouseMoveEvent(QMouseEvent *event) override {
if (pressed) {
QPoint pos = event->pos();
xMove += pos.x() - oldPos.x();
yMove += pos.y() - oldPos.y();
oldPos = pos;
update();
}
}
void mouseReleaseEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
pressed = false;
}
}
private slots:
void zoomIn() {
zoomValue = qMin(zoomValue + 0.1, 5.0);
}
void zoomOut() {
zoomValue = qMax(zoomValue - 0.1, 0.1);
}
private:
void paintEvent(QPaintEvent *event) override
{
QLabel::paintEvent(event);
QPainter painter(this);
if (!originalPixmap.isNull())
{
QPixmap scaledPixmap = originalPixmap.scaled(originalPixmap.width() * zoomValue,
originalPixmap.height() * zoomValue,Qt::KeepAspectRatio,Qt::SmoothTransformation);
QRect targetRect(xMove, yMove, scaledPixmap.width(), scaledPixmap.height());
painter.drawPixmap(targetRect.topLeft(), scaledPixmap);
}
}
};
调用方式
Mat src = imread("123.bmp");
QImage qImage = cvMatToQImage(src);
ui.label_CameraShow->setPixmap(QPixmap::fromImage(qImage));
Mat转Qimage
QImage cvMatToQImage(cv::Mat inMat)
{
switch (inMat.type()) {
case CV_8UC4: {
QImage image(inMat.data, inMat.cols, inMat.rows, static_cast<int>(inMat.step), QImage::Format_ARGB32);
return image;
}
case CV_8UC3: {
QImage image(inMat.data, inMat.cols, inMat.rows, static_cast<int>(inMat.step), QImage::Format_RGB888);
return image.rgbSwapped();
}
case CV_8UC1: {
static QVector<QRgb> sColorTable;
if (sColorTable.isEmpty()) {
for (int i = 0; i < 256; ++i) {
sColorTable.push_back(qRgb(i, i, i));
}
}
QImage image(inMat.data, inMat.cols, inMat.rows, static_cast<int>(inMat.step), QImage::Format_Indexed8);
image.setColorTable(sColorTable);
return image;
}
default:
break;
}
return QImage();
}