Ask everybody to help to reassure,
The header file:
# # ifndef DRAWWIDGET_H
# define DRAWWIDGET_H
# include & lt; QWidget>
# include & lt; QPixmap>
# include & lt; QColor>
# include & lt; QPoint>
# include & lt; QMouseEvent>
# include & lt; QPainter>
The class Drawwidget: public QWidget
{
Q_OBJECT
Public:
Explicit Drawwidget (QWidget * parent=nullptr);
Void mouseMoveEvent (QMouseEvent * event);
Void mousePressEvent (QMouseEvent * event);
Void paintEvent (QPaintEvent * event);
Void resizeEvent (QResizeEvent * event);
Signals:
Public slots:
Void setStyle (int);//set style
Void setWidth (int);//set the width of the
Void setColor (QColor);//set colors
Void the clear ();//clear picture
Private:
QPixmap * pix;
The QPoint startpos;
The QPoint endpos;
Int style;
Int weight;
QColor color;
};
# endif//DRAWWIDGET_H
Source:
# include "drawwidget. H"
Drawwidget: : Drawwidget (QWidget * parent) : QWidget (parent)
{
SetAutoFillBackground (true);//set the background color of form
SetPalette (QPalette (Qt: : white));
Pix=new QPixmap (size ());
Pix - & gt; The fill (Qt: : white);
SetMinimumSize (600, 400);//set the minimum size
}
Void Drawwidget: : setColor (QColor c)
{
Color=c;
}
Void Drawwidget: : setStyle (int s)
{
Style=s;
}
Void Drawwidget: : setWidth (int w)
{
Weight=w;
}
Void Drawwidget: : mousePressEvent (QMouseEvent * event)
{
Startpos=event - & gt; Pos ();
}
Void Drawwidget: : mouseMoveEvent (QMouseEvent * event)
{
QPainter * painter=new QPainter;
QPen pen;
Pen. SetStyle (Qt: : PenStyle style);
Pen. SetWidth (weight);
Pen. SetColor (color);
Painter - & gt; The begin (pix);
Painter - & gt; SetPen (pen).
//draw lines
Painter - & gt; DrawLine (startpos, event - & gt; Pos ());
Painter - & gt; The end ();
Startpos=event - & gt; Pos ();
The update ();
}
Void Drawwidget: : paintEvent (QPaintEvent * event)//drawing event
{
QPainter p (this);
Conviction yourself rawPixmap (QPoint (0, 0), * pix).
}
Void Drawwidget: : resizeEvent (QResizeEvent * event)
{
If (height () & gt; Pix - & gt; Height () | | width () & gt; Pix - & gt; Width ())
{
QPixmap * newpix=new QPixmap (size ());
Newpix - & gt; The fill (Qt: : white);
QPainter p (newpix);
Conviction yourself rawPixmap (QPoint (0, 0), * pix).
Pix=newpix;
}
QWidget: : resizeEvent (event);//finish the rest work
}
Void Drawwidget: : clear ()
{
QPixmap * clearpix=new QPixmap (size ());
Clearpix - & gt; The fill (Qt: : white);
Pix=clearpix;
The update ();
}
CodePudding user response:
Reference: https://blog.csdn.net/taiyang1987912/article/details/29271549