当前位置:   article > 正文

QT图形视图框架:限制图形项不重叠_qgraphicsview防止重叠

qgraphicsview防止重叠
  1. QVariant pixmapItem::itemChange(GraphicsItemChange change, const QVariant &value)
  2. {
  3. if ((change == ItemPositionChange || change == ItemPositionHasChanged) && scene()) // 控件发生移动
  4. {
  5. QPointF newPos = value.toPointF();
  6. QRectF rect(0, 0, scene()->width(), scene()->height());
  7. QList<QGraphicsItem *> list = collidingItems();//碰撞列表
  8. if(list.size() > 0)
  9. {
  10. QGraphicsItem * otherItem = list.first();
  11. QRectF otherItemRect = otherItem->boundingRect();
  12. QRectF otherRect = QRectF(otherItem->x(),otherItem->y(),otherItemRect.width(),otherItemRect.height());
  13. if(otherRect.contains(newPos))//左上角
  14. {
  15. QPointF tempPoint = otherRect.bottomRight() - newPos;
  16. if(abs(tempPoint.x()) > abs(tempPoint.y()))
  17. {
  18. newPos.setY(otherItem->y() + otherRect.height() + 2);
  19. }
  20. else
  21. {
  22. newPos.setX(otherItem->x() + otherRect.width() + 2);
  23. }
  24. this->setPos(newPos);
  25. return newPos;
  26. }
  27. QRectF thisRectF = boundingRect();
  28. QPointF nowPos = QPointF(newPos.x() + thisRectF.width(),newPos.y());
  29. if(otherRect.contains(nowPos))//右上角
  30. {
  31. QPointF tempPoint = otherRect.bottomLeft() - nowPos;
  32. if(abs(tempPoint.x()) > abs(tempPoint.y()))
  33. {
  34. newPos.setY(otherItem->y() + otherRect.height() + 2);
  35. }
  36. else
  37. {
  38. newPos.setX(otherItem->x() - thisRectF.width() - 2);
  39. }
  40. this->setPos(newPos);
  41. return newPos;
  42. }
  43. nowPos = QPointF(newPos.x(),newPos.y() + thisRectF.height());
  44. if(otherRect.contains(nowPos))//左下角
  45. {
  46. QPointF tempPoint = otherRect.topRight() - nowPos;
  47. if(abs(tempPoint.x()) > abs(tempPoint.y()))
  48. {
  49. newPos.setY(otherItem->y() - thisRectF.height() - 2);
  50. }
  51. else
  52. {
  53. newPos.setX(otherItem->x() + otherRect.width() + 2);
  54. }
  55. this->setPos(newPos);
  56. return newPos;
  57. }
  58. nowPos = QPointF(newPos.x() + thisRectF.width(),newPos.y() + thisRectF.height());
  59. if(otherRect.contains(nowPos))//右下角
  60. {
  61. QPointF tempPoint = otherRect.topLeft() - nowPos;
  62. if(abs(tempPoint.x()) > abs(tempPoint.y()))
  63. {
  64. newPos.setY(otherItem->y() - thisRectF.height() - 2);
  65. }
  66. else
  67. {
  68. newPos.setX(otherItem->x() - otherRect.width() - 2);
  69. }
  70. this->setPos(newPos);
  71. return newPos;
  72. }
  73. }
  74. }
  75. return QGraphicsObject::itemChange(change, value);
  76. }

效果:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/916040
推荐阅读
相关标签
  

闽ICP备14008679号