QGraphicsView使用的问题

环境

QT5.15.2+VS2019_64

最近使用QGraphicsView时遇到了一些问题,特此记录.

功能和问题如下:

1.实现在鼠标当前位置为中心缩放

核心就是记录鼠标位置对应ViewPos,先缩放(以视图中心),然后根据记录位置,将场景移动到鼠标位置即可.

auto preViewPos = mapFromGlobal(QCursor::pos());
auto preScenePos = mapToScene(preViewPos);
scale(ratio, ratio);
m_scene->setSceneRect(mapToScene(rect()).boundingRect());
auto newScenePos = mapToScene(preViewPos);
auto disPos = newScenePos -preScenePos ;

m_scene->setSceneRect(sceneRect().x() - disPos.x(), sceneRect().y() - disPos.y(), sceneRect().width(),sceneRect().height());

2. 实现鼠标左键平移功能

实现View的MousePressEvent和MouseMoveEvent功能,即可

void MousePressEvent(QMouseEvent* event)
{
    if(event->button() == Qt::LeftButton)
{
    m_lastPos = event->globalPos();
}

}
void MouseMoveEvent(QMouseEvent* event)
{
    if(event->buttons()& Qt::LeftButton)
{
    auto ePos = event->globalPos();
    double dx = ePos.x()-m_lastPos.x();
    double dy = ePos.y()-m_lastPos.y();

    //此种方法是有时有问题的,我的错误表现是放大后移动时最终矩形的大小会变化,导致移动与目标不一致,换下面一种
    auto rect = scene()->sceneRect();
    //auto polyon = mapFromScene(rect);
    //polyon.translate(-dx,-dy);
    //scene()->setSceneRect(mapToScene(polyon).toPolyon().boundingRect());

    //修改为移动区域的某一点
    auto topLeftPos = mapFromScene(rect.topLeft());
    topLeftPos -= QPoint(dx, dy);
    auto newTopLeft = mapToScene(topLeftPos);
    auto newRect = rect;
    newRect.moveTopLeft(newTopLeft );
    scene()->setSceneRect(newRect);
    m_lastPos = ePos ;
}

}

3.使用QGraphicsItemGroup时分别设置子Item为可选中,未设置Group标志,Item始终无法选中

  1. 尝试设置Group标志,和Item标志,发现只能组选Group,无法单选子Item;
  2. 将Item直接添加到Scene中,就可以了.

4. 往QGraphicsScene中频繁addItem和RemoveItem会导致内存增加,如果需要频繁操作,最好用缓存,采用线控的方式来控制.

特此记录.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值