#include "MyPaint.h"
#include <QPainter>
#include <QMouseEvent>
MyPaint::MyPaint(QWidget *parent):QWidget(parent)
{
}
void MyPaint::mousePressEvent(QMouseEvent *event) //鼠标按下的时候新增加一条线,并记录起点
{
std::vector<QPoint> line;
line.push_back(event->pos());
_lines.push_back(line);
}
void MyPaint::mouseMoveEvent(QMouseEvent *event)//鼠标移动的时候新增加点
{
auto &line = _lines[_lines.size() - 1];
line.push_back(event->pos());
update(); //更新,重新绘制窗口,自动调用paintEvent
}
void MyPaint::mouseReleaseEvent(QMouseEvent *event)
{
auto &line = _lines[_lines.size() - 1];
line.push_back(event->pos());
}
void MyPaint::paintEvent(QPaintEvent *event) //绘制所有的线
{
//QPainter painter(this);
//painter.setPen(QPen(Qt::red, 3, Qt::DashLine));
//painter.setBrush(Qt::blue);
//painter.drawRect(QRect(10, 10, 100, 30));
//painter.drawEllipse(130, 10, 50, 50);
//painter.drawLine(QLine(200, 10, 300, 20));
//painter.drawText(QPoint(10, 70), "hello" );
QPainter painter(this);
painter.setPen(QPen(Qt::green, 3));
for (const auto &line : _lines)
{
for (int i=0;i<line.size()-1;i++)
{
painter.drawLine(line.at(i), line.at(i + 1));
}
}
}
|