Qt实现画笔功能

用Qt实现在窗口上画线,类似于画笔功能。

  • 头文件
#ifndef MyPaint_h__
#define MyPaint_h__

#include 

class MyPaint :public QWidget
{
	Q_OBJECT
public:
	MyPaint(QWidget *parent = nullptr);

	void mousePressEvent(QMouseEvent *event);
	void mouseMoveEvent(QMouseEvent *event);
	void mouseReleaseEvent(QMouseEvent *event);
	void paintEvent(QPaintEvent *event);

private:
	std::vector<std::vector<QPoint>> _lines;

};

#endif // MyPaint_h__

  • 实现
#include "MyPaint.h"
#include 
#include 


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));
		}
	}
}


  • 效果
    Qt实现画笔功能_第1张图片

你可能感兴趣的:(Qt)