qt控件学习之graphicsView

graphicsView是 Qt 中用于显示和操作图形项的高级视图类。它与 QGraphicsScene 和 QGraphicsItem 一起构成了 Qt 的图形视图框架(Graphics View Framework)。这个框架允许你创建复杂的、可交互的 2D 图形场景,并提供了丰富的功能,如缩放、平移、选择、拖拽等。
此处实现一下缩放和平移。
缩放要重写wheelEvent事件
平移重写鼠标事件mousePressEvent
setDragMode(QGraphicsView::ScrollHandDrag);// 开启拖动模式
注意要在mouseMoveEvent
setDragMode(QGraphicsView::NoDrag);// 关闭拖动模式
下面的完整代码

class MyGraphicsView:public QGraphicsView
{
    Q_OBJECT
public:
    MyGraphicsView(QWidget* parent);
    ~MyGraphicsView();
protected:
    // 鼠标左击
    void mousePressEvent(QMouseEvent *event) override;
    // 鼠标释放
    void mouseReleaseEvent(QMouseEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;
};
void MyGraphicsView::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton&&isZoomEnabled) {
        // 开启拖动模式
        setDragMode(QGraphicsView::ScrollHandDrag);
    }
    //最后调用基类mouseMoveEvent函数,保留鼠标释放事件处理逻辑
    QGraphicsView::mousePressEvent(event);
}
void MyGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        // 关闭拖动模式
        setDragMode(QGraphicsView::NoDrag);
    }
    //最后调用基类mouseReleaseEvent函数,保留鼠标释放事件处理逻辑
    QGraphicsView::mouseReleaseEvent(event);
}

void MyGraphicsView::wheelEvent(QWheelEvent *event)
{
    // Get the current scale factor
    double scaleFactor = 1.1; // Zoom in/out by 10% per wheel step

    // Determine the direction of the zoom
    if (event->angleDelta().y() > 0) {
        // Zoom in
        this->scale(scaleFactor, scaleFactor);
    } else {
        // Zoom out
        this->scale(1.0 / scaleFactor, 1.0 / scaleFactor);
    }
    // Center the zoom at the mouse cursor position
    QPointF mousePos = event->position();
    QPointF scenePos = this->mapToScene(mousePos.toPoint());
    this->centerOn(scenePos);
    QGraphicsView::wheelEvent(event);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值