移动正常执行,但是鼠标在矩形边框上时可拉伸矩形大小没有实现
时间: 2024-04-15 09:28:39 浏览: 125
VC++6.0实现动态画矩形,选中,更改大小,随鼠标移动
3星 · 编辑精心推荐
抱歉,我犯了一个错误。在修改的代码中,我忽略了在矩形边框上进行大小调整的逻辑。以下是修复后的代码:
```cpp
#pragma once
#include <QGraphicsItem>
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
class GraphicsItem : public QGraphicsRectItem
{
public:
GraphicsItem(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;
bool m_bMoving;
};
```
我们添加了一个新的成员变量m_bMoving,用于判断是否处于移动状态。
```cpp
#include "GraphicsItem.h"
GraphicsItem::GraphicsItem(QGraphicsItem* parent)
: QGraphicsRectItem(parent)
{
setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
m_bResizing = false;
m_bMoving = false;
}
void GraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
m_pressPos = event->pos();
m_originalRect = rect();
if (m_originalRect.contains(m_pressPos))
{
m_bMoving = true;
setCursor(Qt::OpenHandCursor);
}
else if (m_originalRect.adjusted(-5, -5, 5, 5).contains(m_pressPos))
{
m_bResizing = true;
setCursor(Qt::SizeFDiagCursor);
}
QGraphicsRectItem::mousePressEvent(event);
}
void GraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
if (m_bMoving)
{
QPointF delta = event->pos() - m_pressPos;
moveBy(delta.x(), delta.y());
}
else 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 GraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
m_bMoving = false;
m_bResizing = false;
setCursor(Qt::ArrowCursor);
QGraphicsRectItem::mouseReleaseEvent(event);
}
```
现在,您可以使用修复后的GraphicsItem类来创建具有拖动和调整大小功能的矩形对象了。
阅读全文