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)); } } }
效果
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。