这篇文章主要为大家详细介绍了Qt实现画笔功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
用Qt实现在窗口上画线,类似于画笔功能。
头文件
#ifndef MyPaint_h__
#define MyPaint_h__
#include <QtWidgets/QWidget>
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 <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));
}
}
}
效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:Qt实现画笔功能


基础教程推荐
猜你喜欢
- C++实战之二进制数据处理与封装 2023-05-29
- [c语言-函数]不定量参数 2023-09-08
- centos 7 vscode cmake 编译c++工程 2023-09-17
- C语言编程C++旋转字符操作串示例详解 2022-11-20
- C语言 详解字符串基础 2023-03-27
- 全面了解C语言 static 关键字 2023-03-26
- C++实现ETW进行进程变动监控详解 2023-05-15
- C语言实现宾馆管理系统课程设计 2023-03-13
- [C语言]二叉搜索树 2023-09-07
- 带你深度走入C语言取整以及4种函数 2022-09-17