本文主要是介绍QPainter实现画图板原型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
自己的画图板功能很简单,实现鼠标左键画图,右键撤销最后的一笔.
效果如下图:
/*---------------MyPainter.h---------------*/
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPainter>
#include <QMouseEvent>
#include <QPaintEvent>class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();void paintEvent(QPaintEvent *);void mousePressEvent(QMouseEvent *);void mouseReleaseEvent(QMouseEvent *);void mouseMoveEvent(QMouseEvent *);QVector< QVector<QPoint> > _lines;private:bool move;
};#endif // WIDGET_H/*---------------MyPainter.h---------------*/
/*---------------MyPainter.cpp---------------*/
#include "Widget.h"Widget::Widget(QWidget *parent) :QWidget(parent)
{this->setStyleSheet("background-color:white;");move = false;
}Widget::~Widget()
{}void Widget::paintEvent(QPaintEvent *)
{QPainter p(this);for(int i = 0; i < _lines.size(); ++i){const QVector<QPoint>& line = _lines.at(i);for(int j=0; j < line.size()-1; ++j){p.drawLine(line.at(j), line.at(j+1));}}}void Widget::mousePressEvent(QMouseEvent *ev)
{if(ev->button() == Qt::LeftButton){QVector<QPoint> line;_lines.append(line);QVector<QPoint>& lastLine = _lines.last();lastLine.append(ev->pos());}if(ev->button() == Qt::RightButton){move = true;if(_lines.size() != 0){_lines.pop_back();}update();}}void Widget::mouseReleaseEvent(QMouseEvent *ev)
{if(ev->button() == Qt::LeftButton){QVector<QPoint>& lastLine = _lines.last();lastLine.append(ev->pos());}if(ev->button() == Qt::RightButton){move = false;}}void Widget::mouseMoveEvent(QMouseEvent *ev)
{if(_lines.size() > 0 && ( move == false )){QVector<QPoint>& lastLine = _lines.last();lastLine.append(ev->pos());update();}}/*---------------MyPainter.cpp---------------*/
/*---------------main.cpp---------------*/
#include "Widget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}/*---------------main.cpp---------------*/
这篇关于QPainter实现画图板原型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!