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始终无法选中
4. 往QGraphicsScene中频繁addItem和RemoveItem会导致内存增加,如果需要频繁操作,最好用缓存,采用线控的方式来控制.
特此记录.