#include "ResizableRectItem.h" GraphicsItems::GraphicsItems(QGraphicsItem* parent) : QGraphicsRectItem(parent) { setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable); m_bResizing = false; } void GraphicsItems::mousePressEvent(QGraphicsSceneMouseEvent* event) { m_pressPos = event->pos(); m_originalRect = rect(); if (m_originalRect.contains(m_pressPos)) { m_bResizing = true; setCursor(Qt::SizeAllCursor); } else { m_bResizing = false; setCursor(Qt::ClosedHandCursor); } QGraphicsRectItem::mousePressEvent(event); } void GraphicsItems::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { if (m_bResizing) { QPointF delta = event->pos() - m_pressPos; QRectF newRect = m_originalRect.adjusted(0, 0, delta.x(), delta.y()); setRect(newRect); } else { QGraphicsRectItem::mouseMoveEvent(event); } } void GraphicsItems::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { m_bResizing = false; setCursor(Qt::ArrowCursor); QGraphicsRectItem::mouseReleaseEvent(event); }修改这个类,改为鼠标在矩形类可拖动矩形位置,在矩形边缘可拉伸矩形大小
时间: 2024-04-15 15:28:14 浏览: 195
要修改ResizableRectItem类,使其能够在矩形边缘拉伸大小并在矩形内部拖动位置,您可以进行以下更改:
```cpp
#pragma once
#include <QGraphicsItem>
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
class ResizableRectItem : public QGraphicsRectItem
{
public:
ResizableRectItem(QGraphicsItem* parent = nullptr);
protected:
void mousePressEvent(QGraphicsSceneMouseEvent* event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override;
private:
QPointF m_pressPos;
QRectF m_originalRect;
bool m_bResizing;
};
```
在这个修改过的类中,我们将类名从GraphicsItems改为ResizableRectItem,并将其作为一个独立的类。
接下来,我们需要在类的构造函数中添加缩放和移动的标志:
```cpp
ResizableRectItem::ResizableRectItem(QGraphicsItem* parent)
: QGraphicsRectItem(parent)
{
setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
m_bResizing = false;
}
```
然后,我们修改鼠标事件处理函数以实现拉伸和移动功能:
```cpp
void ResizableRectItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
m_pressPos = event->pos();
m_originalRect = rect();
if (m_originalRect.contains(m_pressPos))
{
m_bResizing = true;
setCursor(Qt::SizeAllCursor);
}
else
{
m_bResizing = false;
setCursor(Qt::ClosedHandCursor);
}
QGraphicsRectItem::mousePressEvent(event);
}
void ResizableRectItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
if (m_bResizing)
{
QPointF delta = event->pos() - m_pressPos;
QRectF newRect = m_originalRect.adjusted(0, 0, delta.x(), delta.y());
setRect(newRect);
}
else
{
QGraphicsRectItem::mouseMoveEvent(event);
}
}
void ResizableRectItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
m_bResizing = false;
setCursor(Qt::ArrowCursor);
QGraphicsRectItem::mouseReleaseEvent(event);
}
```
这些鼠标事件处理函数与之前的示例相同,以实现在矩形边缘拉伸大小和在矩形内部拖动位置的功能。
现在,您可以使用修改后的ResizableRectItem类来创建具有可拉伸大小和可拖动位置功能的矩形对象了。
阅读全文