• QGraphicsView使用的问题


    环境

    QT5.15.2+VS2019_64

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

    功能和问题如下:

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

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

    1. auto preViewPos = mapFromGlobal(QCursor::pos());
    2. auto preScenePos = mapToScene(preViewPos);
    3. scale(ratio, ratio);
    4. m_scene->setSceneRect(mapToScene(rect()).boundingRect());
    5. auto newScenePos = mapToScene(preViewPos);
    6. auto disPos = newScenePos -preScenePos ;
    7. m_scene->setSceneRect(sceneRect().x() - disPos.x(), sceneRect().y() - disPos.y(), sceneRect().width(),sceneRect().height());

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

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

    1. void MousePressEvent(QMouseEvent* event)
    2. {
    3. if(event->button() == Qt::LeftButton)
    4. {
    5. m_lastPos = event->globalPos();
    6. }
    7. }
    8. void MouseMoveEvent(QMouseEvent* event)
    9. {
    10. if(event->buttons()& Qt::LeftButton)
    11. {
    12. auto ePos = event->globalPos();
    13. double dx = ePos.x()-m_lastPos.x();
    14. double dy = ePos.y()-m_lastPos.y();
    15. //此种方法是有时有问题的,我的错误表现是放大后移动时最终矩形的大小会变化,导致移动与目标不一致,换下面一种
    16. auto rect = scene()->sceneRect();
    17. //auto polyon = mapFromScene(rect);
    18. //polyon.translate(-dx,-dy);
    19. //scene()->setSceneRect(mapToScene(polyon).toPolyon().boundingRect());
    20. //修改为移动区域的某一点
    21. auto topLeftPos = mapFromScene(rect.topLeft());
    22. topLeftPos -= QPoint(dx, dy);
    23. auto newTopLeft = mapToScene(topLeftPos);
    24. auto newRect = rect;
    25. newRect.moveTopLeft(newTopLeft );
    26. scene()->setSceneRect(newRect);
    27. m_lastPos = ePos ;
    28. }
    29. }

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

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

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

    特此记录.

  • 相关阅读:
    Java并发编程—并发和并行、线程上下文
    线程的基本操作(三)
    OPENCV实战分水岭法二
    Leetcode 828. 统计子串中的唯一字符
    【触想智能】工控一体机与5G物联网技术结合是未来发展趋势
    数组实现邻接表(java)
    本地 HTTP 文件服务器的简单搭建 (deno/std)
    详解欧拉计划第95题:亲和数链
    xgboost 与 lgbm
    当PBlaze6 6920 Raid阵列遇到FC SAN
  • 原文地址:https://blog.csdn.net/guomingbing12/article/details/133093499