You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 regels
2.5 KiB

  1. #include "hmiwidget.h"
  2. #include <QDebug>
  3. #include<QMenu>
  4. #include<QGraphicsScene>
  5. // ResizableShape 模板类的实现
  6. template <typename BaseShape>
  7. ResizableShape<BaseShape>::ResizableShape(qreal x, qreal y, qreal w, qreal h)
  8. : BaseShape(x, y, w, h), resizing(false)
  9. {
  10. this->setFlag(QGraphicsItem::ItemIsMovable, true);
  11. this->setFlag(QGraphicsItem::ItemIsSelectable, true);
  12. this->setAcceptHoverEvents(true);
  13. }
  14. template <typename BaseShape>
  15. void ResizableShape<BaseShape>::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
  16. {
  17. if (isInResizeArea(event->pos())) {
  18. this->setCursor(Qt::SizeFDiagCursor);
  19. } else {
  20. this->setCursor(Qt::SizeAllCursor);
  21. }
  22. BaseShape::hoverMoveEvent(event);
  23. }
  24. template <typename BaseShape>
  25. bool ResizableShape<BaseShape>::isInResizeArea(const QPointF &pos) const
  26. {
  27. QRectF r = this->rect();
  28. QRectF resizeArea(r.bottomRight() - QPointF(20, 20), r.bottomRight());
  29. return resizeArea.contains(pos);
  30. }
  31. template <typename BaseShape>
  32. void ResizableShape<BaseShape>::mousePressEvent(QGraphicsSceneMouseEvent *event)
  33. {
  34. if (isInResizeArea(event->pos())) {
  35. resizing = true;
  36. this->setCursor(Qt::SizeFDiagCursor);
  37. } else {
  38. resizing = false;
  39. this->setCursor(Qt::SizeAllCursor);
  40. BaseShape::mousePressEvent(event);
  41. }
  42. }
  43. template <typename BaseShape>
  44. void ResizableShape<BaseShape>::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
  45. {
  46. if (resizing) {
  47. QRectF newRect = this->rect();
  48. newRect.setBottomRight(event->pos());
  49. this->setRect(newRect);
  50. } else {
  51. BaseShape::mouseMoveEvent(event);
  52. }
  53. }
  54. template <typename BaseShape>
  55. void ResizableShape<BaseShape>::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
  56. {
  57. resizing = false;
  58. this->setCursor(Qt::SizeAllCursor);
  59. BaseShape::mouseReleaseEvent(event);
  60. }
  61. template <typename BaseShape>//虚函数
  62. void ResizableShape<BaseShape>::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
  63. {
  64. BaseShape::paint(painter, option, widget);
  65. }
  66. // ResizableRectangle 实现
  67. ResizableRectangle::ResizableRectangle(qreal x, qreal y, qreal w, qreal h)
  68. : ResizableShape<QGraphicsRectItem>(x, y, w, h)
  69. {
  70. }
  71. // ResizableEllipse 实现
  72. ResizableEllipse::ResizableEllipse(qreal x, qreal y, qreal w, qreal h)
  73. : ResizableShape<QGraphicsEllipseItem>(x, y, w, h)
  74. {
  75. }
  76. // 显式实例化模板类
  77. template class ResizableShape<QGraphicsRectItem>;
  78. template class ResizableShape<QGraphicsEllipseItem>;