qt创建矩形的graphicsitem使得它可以被拖动,被拖拽缩放,被拖动旋转点旋转
时间: 2023-12-07 18:02:13 浏览: 252
可以通过继承 QGraphicsItem 实现这个功能。以下是一个简单的示例:
```cpp
#include <QGraphicsItem>
#include <QPainter>
class RectangleItem : public QGraphicsItem
{
public:
RectangleItem(QGraphicsItem *parent = nullptr)
: QGraphicsItem(parent)
, m_rect(0, 0, 100, 100)
, m_rotationPoint(m_rect.center())
{
setFlags(ItemIsMovable | ItemIsSelectable | ItemSendsGeometryChanges);
setAcceptHoverEvents(true);
}
QRectF boundingRect() const override
{
return m_rect.adjusted(-5, -5, 5, 5);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setRenderHint(QPainter::Antialiasing);
painter->setPen(Qt::black);
painter->setBrush(Qt::lightGray);
painter->drawRect(m_rect);
// 画旋转点
painter->setBrush(Qt::black);
painter->drawEllipse(m_rotationPoint, 5, 5);
}
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override
{
if (change == ItemPositionChange || change == ItemRotationChange) {
// 更新旋转点的位置
m_rotationPoint = mapToScene(m_rect.center());
}
return QGraphicsItem::itemChange(change, value);
}
void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override
{
// 鼠标在旋转点上时,更改鼠标形状
if (QLineF(event->pos(), m_rotationPoint).length() < 10) {
setCursor(Qt::PointingHandCursor);
} else {
setCursor(Qt::ArrowCursor);
}
}
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
{
if (QLineF(event->pos(), m_rotationPoint).length() < 10) {
// 点击旋转点,记录下初始角度
QPointF center = mapToScene(m_rect.center());
m_initialAngle = QLineF(center, event->scenePos()).angle();
} else {
QGraphicsItem::mousePressEvent(event);
}
}
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override
{
if (event->buttons() & Qt::LeftButton && isSelected()) {
if (QLineF(event->pos(), m_rotationPoint).length() < 10) {
// 拖动旋转点,计算角度差并旋转矩形
QPointF center = mapToScene(m_rect.center());
qreal angle = QLineF(center, event->scenePos()).angle();
setRotation(rotation() + angle - m_initialAngle);
m_initialAngle = angle;
} else {
QGraphicsItem::mouseMoveEvent(event);
}
}
}
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
{
QGraphicsItem::mouseReleaseEvent(event);
prepareGeometryChange();
}
private:
QRectF m_rect; // 矩形的区域
QPointF m_rotationPoint; // 旋转点的位置
qreal m_initialAngle = 0; // 拖拽旋转点时记录下来的初始角度
};
```
在 `QGraphicsView` 中添加该 item:
```cpp
QGraphicsScene *scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
RectangleItem *item = new RectangleItem;
scene->addItem(item);
```
这样就可以通过鼠标拖拽、缩放、旋转点旋转来操作该矩形了。
阅读全文