qt qgraphicsview 移动圆弧
时间: 2023-07-05 16:32:23 浏览: 109
要在Qt的QGraphicsView中移动圆弧,可以创建一个自定义的QGraphicsItem子类,重写它的paint()和boundingRect()函数,并在其中实现圆弧的绘制和移动逻辑。
以下是一个简单的示例代码,它创建了一个圆弧,并通过鼠标拖动来移动它:
```
#include <QtWidgets>
class ArcItem : public QGraphicsItem
{
public:
ArcItem(qreal x, qreal y, qreal width, qreal height, qreal startAngle, qreal spanAngle, QGraphicsItem *parent = nullptr)
: QGraphicsItem(parent),
m_rect(x, y, width, height),
m_startAngle(startAngle),
m_spanAngle(spanAngle),
m_mousePressed(false)
{
setFlags(ItemIsMovable | ItemSendsGeometryChanges);
}
QRectF boundingRect() const override
{
return m_rect;
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
painter->drawArc(m_rect, m_startAngle * 16, m_spanAngle * 16);
}
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override
{
if (change == ItemPositionChange && scene()) {
QPointF newPos = value.toPointF();
QRectF rect = scene()->sceneRect();
if (!rect.contains(newPos)) {
// Keep the item inside the scene rect.
newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
{
m_mousePressed = true;
QGraphicsItem::mousePressEvent(event);
}
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
{
m_mousePressed = false;
QGraphicsItem::mouseReleaseEvent(event);
}
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override
{
if (m_mousePressed) {
QPointF delta = event->pos() - event->lastPos();
setPos(pos() + delta);
}
QGraphicsItem::mouseMoveEvent(event);
}
private:
QRectF m_rect;
qreal m_startAngle;
qreal m_spanAngle;
bool m_mousePressed;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
scene.setSceneRect(-100, -100, 200, 200);
ArcItem *arc = new ArcItem(-50, -50, 100, 100, 30, 120);
scene.addItem(arc);
QGraphicsView view(&scene);
view.setRenderHint(QPainter::Antialiasing);
view.setDragMode(QGraphicsView::RubberBandDrag);
view.show();
return a.exec();
}
```
这个示例创建了一个圆弧,定义了它的位置、大小和起始角度、跨越角度。在重写的mousePressEvent()、mouseReleaseEvent()和mouseMoveEvent()函数中,实现了通过鼠标拖动来移动圆弧的逻辑。
阅读全文