QT——画一个三角形

.h

#pragma once

#include 
#include 
#include 
#include 
#include 
#include 
#include "ui_QtWidgetsApplication1.h"

class QtWidgetsApplication1 : public QWidget
{
    Q_OBJECT

public:
    QtWidgetsApplication1(QWidget *parent = Q_NULLPTR);
	virtual void paintEvent(QPaintEvent *event) override;
	//鼠标按下
	void mousePressEvent(QMouseEvent *e);
	//鼠标移动
	void mouseMoveEvent(QMouseEvent *e);
	//鼠标抬起
	void mouseReleaseEvent(QMouseEvent *e);

private:
    Ui::QtWidgetsApplication1Class ui;
	QPoint lineStartPoint;          //画线起点
	QPoint lineEndPoint;            //画线终点
	QColor lineColor;               //线条颜色
	int lineSize;                  //5种线型
	bool isPressed;
	QVectorpointList;

};

.cpp

#include "QtWidgetsApplication1.h"

QtWidgetsApplication1::QtWidgetsApplication1(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
	this->lineStartPoint = QPoint(0, 0);
	this->lineEndPoint = QPoint(0, 0);
	this->lineColor = QColor(Qt::black);
	this->lineSize = 3;

}
void QtWidgetsApplication1::paintEvent(QPaintEvent *event)
{
	QPainter painter(this);
	QPen pen;
	pen.setColor(lineColor);
	pen.setWidth(lineSize);
	painter.setPen(pen);
	painter.drawLine(lineStartPoint, lineEndPoint);
	for (int i = 0; i < pointList.size() - 1; i++)
	{
		painter.drawLine(pointList[i], pointList[i+1]);
		i++;
	}
}

void QtWidgetsApplication1::mousePressEvent(QMouseEvent * e)
{
	lineStartPoint = e->pos();
	lineEndPoint = e->pos();
	//在图片上绘制
	isPressed = true;
}

void QtWidgetsApplication1::mouseMoveEvent(QMouseEvent * e)
{
	if (isPressed)
	{
		lineEndPoint = e->pos();
		update();
	}
}

void QtWidgetsApplication1::mouseReleaseEvent(QMouseEvent * e)
{
	isPressed = false;
	update();
	pointList.append(lineStartPoint);
	pointList.append(lineEndPoint);
}




你可能感兴趣的:(QT,qt,ui,c++)