用的Qt的中的的的paintEvent绘图,通过坐标系的变换来实现对图像的位置变化,通过滚轮事件对图像的大小进行缩放具体代码如下:
新建Qt Widget应用程序
新增头文件:
#include <QBrush>
#include <QPen>
#include <QPainter>
#include <QMouseEvent>
#include <QDebug>
#include <QWheelEvent>
mainwindow.h中这样写:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *ev);
void mouseMoveEvent(QMouseEvent *ev);
void wheelEvent(QWheelEvent *ev);
void zoomPixmap();
private:
Ui::MainWindow *ui;
QRect rect;
float zoom;//缩放系数
QPoint CurrentCoordinates,LastCoordinates;//当前的坐标,上一次移动的坐标
};
mainwindow.cpp中这样写:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//初始化矩形的尺寸和放大缩小的系数
rect.setRect(50,50,50,50);
zoom = 1.0;
}
MainWindow::~MainWindow()
{
delete ui;
}
//绘图
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter p(this);
QBrush brush;
QPen pen;
//设置坐标系
p.translate(CurrentCoordinates);
//反锯齿
p.setRenderHint(QPainter::Antialiasing);
//设置画笔颜色,边框的颜色
brush.setColor(Qt::blue);
//设置填充的风格,不设置默认不填充
brush.setStyle(Qt::SolidPattern);
//设置画刷的颜色,矩形填充的颜色
pen.setColor(Qt::red);
//将画笔和画刷给QPainter
p.setPen(pen);
p.setBrush(brush);
//画矩形
p.drawRect(rect);
}
//放大缩小函数
void MainWindow::zoomPixmap()
{
float width,hight;
width = rect.width();
hight = rect.height();
width = width*zoom;
hight = hight*zoom;
rect.setWidth(width);
rect.setHeight(hight);
}
//鼠标按键按下事件
void MainWindow::mousePressEvent(QMouseEvent *ev)
{
//鼠标按下时记录当前按下的坐标
if(ev->button() == Qt::LeftButton)
{
if(ev->x()>rect.x() && ev->x()<rect.x()+rect.width())
{
if(ev->y()>rect.y() && ev->y()<rect.y()+rect.height())
{
LastCoordinates = ev->pos();
}
}
}
}
//鼠标滚轮事件
void MainWindow::wheelEvent(QWheelEvent *ev)
{
//如果滚轮向上滚动就放大尺寸
if(ev->delta() > 0)
{
zoom = 1.1;
}
else//如果滚轮向下滚动就缩小尺寸
{
zoom = 0.9;
}
zoomPixmap();
update();
}
//鼠标移动事件
void MainWindow::mouseMoveEvent(QMouseEvent *ev)
{
//当鼠标左键按下且移动
if(ev->buttons() & Qt::LeftButton){
//计算当前需要移动的距离,保存本次的坐标
CurrentCoordinates = CurrentCoordinates - LastCoordinates + ev->pos();
LastCoordinates = ev->pos();
ev->accept();
this->update();
}
}
实现效果: