MaterialBoxGraphicsView.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #ifndef MATERIALBOXGRAPHICSVIEW_H
  2. #define MATERIALBOXGRAPHICSVIEW_H
  3. #include <QGraphicsView>
  4. #include <QGraphicsScene>
  5. #include <QGraphicsRectItem>
  6. #include <QMouseEvent>
  7. #include <QLabel>
  8. #include <QPointer>
  9. #include <QGraphicsItem>
  10. #include <QPainter>
  11. #include <QColor>
  12. #include <QGraphicsSceneEvent>
  13. #include <QDebug>
  14. class BackgroundRect : public QGraphicsItem {
  15. public:
  16. BackgroundRect(int containerWidthdp, int containerHeightdp, int containerWidth, int containerHeight)
  17. : m_containerWidthdp(containerWidthdp), m_containerHeightdp(containerHeightdp), m_containerWidth(containerWidth), m_containerHeight(containerHeight) {
  18. setFlag(QGraphicsItem::ItemIsSelectable);
  19. setFlag(QGraphicsItem::ItemIsMovable, false);
  20. setFlag(QGraphicsItem::ItemIsFocusable, false);
  21. setAcceptedMouseButtons(Qt::NoButton); // 禁用所有鼠标按键
  22. setAcceptHoverEvents(false); // 禁用悬停事件
  23. }
  24. QRectF boundingRect() const override {
  25. return QRectF(m_containerWidthdp, m_containerHeightdp, m_containerWidth, m_containerHeight);
  26. }
  27. void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override ;
  28. private:
  29. int m_containerWidthdp;
  30. int m_containerHeightdp;
  31. int m_containerWidth;
  32. int m_containerHeight;
  33. // 可选:显式忽略所有鼠标事件
  34. void mousePressEvent(QGraphicsSceneMouseEvent* event) override {
  35. event->ignore(); // 允许事件穿透
  36. }
  37. };
  38. class MaterialBoxDie:public QObject, public QGraphicsRectItem{
  39. Q_OBJECT
  40. public:
  41. MaterialBoxDie(int row, int col, int status, qreal weight,qreal height, QGraphicsItem* parent = nullptr);
  42. void setLeftSelected(bool selected);
  43. void setRightSelected(bool selected);
  44. int getRow();
  45. private:
  46. int row, col;
  47. int status;
  48. bool isSelected = false;
  49. // 获取单元格状态颜色
  50. QColor getColorByStatus(int status);
  51. };
  52. class MaterialBoxGraphicsView : public QGraphicsView {
  53. Q_OBJECT
  54. public:
  55. MaterialBoxGraphicsView(QGraphicsScene* scene, QWidget* parent = nullptr);
  56. signals:
  57. void layerRightClicked(int layer);
  58. protected:
  59. void mousePressEvent(QMouseEvent* event) override;
  60. // void mouseMoveEvent(QMouseEvent* event) override;
  61. void mouseReleaseEvent(QMouseEvent* event) override;
  62. void wheelEvent(QWheelEvent* event) override;
  63. // bool eventFilter(QObject *obj, QEvent *event) override;
  64. void clearSeleted();
  65. private:
  66. double scaleFactor; // 当前缩放比例
  67. QPointer<MaterialBoxDie> selectedLeftItem;
  68. QPointer<MaterialBoxDie> selectedRightItem;
  69. };
  70. #endif // MATERIALBOXGRAPHICSVIEW_H