Qt 可拖拽 大小可调 方框
时间: 2023-08-29 10:13:49 浏览: 156
您可以使用Qt中的QGraphicsView和QGraphicsItem来实现可拖拽大小可调的方框。以下是一个简单的示例:
```
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
class ResizableRectItem : public QGraphicsRectItem
{
public:
ResizableRectItem(QGraphicsItem *parent = nullptr) : QGraphicsRectItem(parent)
{
setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsGeometryChanges);
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
{
m_startPos = pos();
m_mousePos = event->scenePos();
m_rect = rect();
QGraphicsRectItem::mousePressEvent(event);
}
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override
{
QPointF delta = event->scenePos() - m_mousePos;
if (isSelected())
{
if (event->modifiers() & Qt::ShiftModifier)
{
if (delta.x() > delta.y())
{
delta.setY(delta.x());
}
else
{
delta.setX(delta.y());
}
}
setPos(m_startPos + delta);
}
QGraphicsRectItem::mouseMoveEvent(event);
}
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
{
QGraphicsRectItem::mouseReleaseEvent(event);
}
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override
{
if (change == ItemPositionChange)
{
QPointF newPos = value.toPointF();
QRectF rect = m_rect.translated(newPos - pos());
setRect(rect);
}
return QGraphicsRectItem::itemChange(change, value);
}
private:
QPointF m_startPos;
QPointF m_mousePos;
QRectF m_rect;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
ResizableRectItem *rectItem = new ResizableRectItem();
rectItem->setRect(0, 0, 100, 100);
scene.addItem(rectItem);
view.show();
return a.exec();
}
```
在这个示例中,我们继承了QGraphicsRectItem并重写了它的mousePressEvent、mouseMoveEvent、mouseReleaseEvent和itemChange函数。在mousePressEvent中,我们记录下方框的位置、鼠标位置和大小。在mouseMoveEvent中,我们根据鼠标移动的距离来更新方框的位置,并根据按下的Shift键来等比例调整方框的大小。在itemChange函数中,我们根据方框的位置变化来调整方框的大小。
阅读全文