Qt--paintEvent下对图形进行移动、缩放

用的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();
    }
}



实现效果:

       


  • 11
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值