QPainter绘制折线,并在折线的两个端点起始位置加上图片
时间: 2024-10-23 16:03:35 浏览: 17
PyQt5利用QPainter绘制各种图形的实例
在Qt中,你可以使用`QPainter`和`QPainterPath`来绘制折线,同时通过`setBrush()`设置颜色并在每个端点使用`drawPixmap()`方法添加图片。下面是一个简单的示例:
**头文件(line_image_item.h):**
```cpp
#ifndef LINE_IMAGE_ITEM_H
#define LINE_IMAGE_ITEM_H
#include <QObject>
#include <QGraphicsObject>
#include <QPainter>
#include <QPixmap>
#include <QPointF>
class LineImageItem : public QObject, public QGraphicsObject
{
Q_OBJECT
Q_PROPERTY(QPointF startPoint READ startPoint WRITE setStartPoint NOTIFY startPointChanged)
Q_PROPERTY(QPointF endPoint READ endPoint WRITE setEndPoint NOTIFY endPointChanged)
public:
explicit LineImageItem(QGraphicsScene *parent = nullptr);
QPointF startPoint() const { return m_startPoint; }
QPointF endPoint() const { return m_endPoint; }
void setStartPoint(const QPointF &point) { m_startPoint = point; emit startPointChanged(); }
void setEndPoint(const QPointF &point) { m_endPoint = point; emit endPointChanged(); }
signals:
void startPointChanged();
void endPointChanged();
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
private:
QPointF m_startPoint;
QPointF m_endPoint;
QPixmap m_pixmap; // 图片资源
};
#endif // LINE_IMAGE_ITEM_H
```
**源文件(line_image_item.cpp):**
```cpp
#include "line_image_item.h"
LineImageItem::LineImageItem(QGraphicsScene *parent) : QGraphicsObject(parent), m_pixmap("path_to_your_image.png") {}
//... 其他方法...
void LineImageItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->save();
// 绘制折线
QPainterPath path;
path.moveTo(m_startPoint);
path.lineTo(m_endPoint);
painter->drawPath(path);
// 设置颜色
painter->setPen(Qt::red); // 修改这里为所需的线条颜色
painter->drawPath(path);
// 在折线两端添加图片
painter->translate(m_startPoint.x(), m_startPoint.y());
painter->drawPixmap(0, 0, m_pixmap.scaledToWidth(32)); // 缩放图片并定位
painter->translate(-m_startPoint.x(), -m_startPoint.y());
painter->translate(m_endPoint.x(), m_endPoint.y());
painter->drawPixmap(0, 0, m_pixmap.scaledToWidth(32));
painter->translate(-m_endPoint.x(), -m_endPoint.y());
painter->restore();
}
```
这个`LineImageItem`类包含了折线的起点和终点属性,以及相关的信号通知。在`paint`方法中,我们先创建一个路径,然后绘制折线,再用红色画笔描边。最后在折线的起始和结束位置添加图片。
阅读全文