QT——画一个三角形

.h

#pragma once

#include <QtWidgets/QWidget>
#include <QPainter>
#include <QMouseEvent>
#include <QVector>
#include <QMap>
#include <QPoint>
#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;
	QVector<QPoint>pointList;

};

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




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值