直接上代码
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QLabel>
#include <QPixmap>
#include <QWidget>
#include <QResizeEvent>
#include <QMouseEvent>
class Widget : public QWidget
{
Q_OBJECT
private:
int x,y;
bool isPress;
QPixmap pixDst;
QPixmap scalePix;
QPixmap pImgScale;
QLabel* labBG;
QLabel* labScale;
public:
Widget(QWidget *parent = nullptr);
~Widget();
protected:
virtual void resizeEvent(QResizeEvent*);
virtual void mousePressEvent(QMouseEvent*);
virtual void mouseReleaseEvent(QMouseEvent*);
virtual void mouseMoveEvent(QMouseEvent*);
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
constexpr int iw=240;
constexpr int ih=240;
constexpr int iep=5;
constexpr int iwCopy = 80;
constexpr int ihCopy = 80;
Widget::Widget(QWidget *parent)
: QWidget(parent),x(0),y(0)
{
isPress=false;
setFixedSize(960,720);
labBG=new QLabel(this);
labScale=new QLabel(this);
//显示图片
QPixmap pixSrc;
pixSrc.load("./bg.jpg");
pixDst=pixSrc.scaled(this->width(),this->height(),Qt::IgnoreAspectRatio);
labBG->setPixmap(pixDst);
}
Widget::~Widget()
{
}
void Widget::resizeEvent(QResizeEvent *event)
{
labScale->resize(iw, ih);
labBG->setGeometry(0,0,this->width(),this->height());
QWidget::resizeEvent(event);
}
void Widget::mousePressEvent(QMouseEvent *event)
{
isPress=true;
QWidget::mousePressEvent(event);
}
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
isPress=false;
labScale->hide();
QWidget::mouseReleaseEvent(event);
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
if(isPress){
if(labScale->isVisible()){}
else{
labScale->show();
}
x = event->pos().x();
if ((x + iw) > width()){
x = x - iw;
x -= iep;
}
else{
x += iep;
}
y = event->pos().y();
if ((y + ih) > height()){
y = y - ih;
y -= iep;
}
else{
y += iep;
}
labScale->move(x, y);
x = event->pos().x() - iwCopy / 2;
y = event->pos().y() - ihCopy / 2;
x = (x < 0) ? 0 : x;
y = (y < 0) ? 0 : y;
scalePix = pixDst.copy(x, y, iwCopy, ihCopy);
pImgScale = scalePix.scaled(iw, ih, Qt::IgnoreAspectRatio);
labScale->setPixmap(pImgScale);
labScale->show();
}
else{
labScale->hide();
}
QWidget::mouseMoveEvent(event);
}