QGraphicsPathItem是Qt框架中图形视图模块的一个强大工具,它允许用户通过QPainterPath对象来定义复杂的图形路径。通过重载的paint()函数和其他成员函数,QGraphicsPathItem提供了丰富的图形绘制和交互功能。
主要方法
- void setPath(const QPainterPath &path)
设置路径。
- QPainterPath path() const
返回当前路径。
- virtual QRectF boundingRect() const override
返回项目的边界矩形,用于确定项目的位置和大小。
- virtual bool contains(const QPointF &point) const override
判断给定的点是否在项目内。
- virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override
使用项目的关联笔刷和画笔绘制路径。
- setPen(const QPen &pen)
设置用于绘制边界的画笔。
- setBrush(const QBrush &brush)
设置用于填充的画刷。
QGraphicsView view;
int x = -200, y = -200;
int w = 400, h = 400;
QGraphicsScene scene(x, y, w, h);
scene.setBackgroundBrush(QBrush(qRgb(173, 241, 174)));
QPen pen(qRgb(140, 159, 141));
pen.setWidth(1);
for (int i = x + 20; i < x + w; i += 20) {
scene.addLine(x, i, x + w, i, pen);
scene.addLine(i, y, i, y + h, pen);
}
QGraphicsItemGroup xAxis;
scene.addItem(&xAxis);
xAxis.addToGroup(new QGraphicsLineItem(x, 0, x + w, 0));
xAxis.addToGroup(new QGraphicsLineItem(x + w - 10, -10, x + w, -1));
xAxis.addToGroup(new QGraphicsLineItem(x + w - 10, 10, x + w, 1));
QGraphicsItemGroup yAxis;
scene.addItem(&yAxis);
yAxis.addToGroup(new QGraphicsLineItem(0, y, 0, y + h));
yAxis.addToGroup(new QGraphicsLineItem(-1, y + h, -10, y + h - 10));
yAxis.addToGroup(new QGraphicsLineItem(1, y + h, 10, y + h - 10));
auto *gi = new QGraphicsPathItem;
gi->setFlag(QGraphicsItem::ItemIsMovable);
QPainterPath path;
path.moveTo(0, 0);
path.cubicTo(120, -20, 60, 100, 120, 80);
gi->setPath(path);
QLinearGradient gLg;
gLg.setStart(0, 0);
gLg.setFinalStop(100, 100);
gLg.setColorAt(0, qRgb(221, 186, 68));
gLg.setColorAt(1, qRgb(221, 226, 68));
gi->setPen(pen);
gi->setBrush(gLg);
gi->setOpacity(0.8);
gi->moveBy(-60, -50);
scene.addItem(gi);
view.setScene(&scene);
view.setRenderHint(QPainter::Antialiasing);
view.setWindowFlag(Qt::WindowMinMaxButtonsHint, false);
view.show();
view.setWindowOpacity(0.8);
qq群交流:698593923
觉得有帮助的话,打赏一下呗。。