源码分析
int Widget::drawType()
{
int ret = NONE;
if(m_freeBtn.isChecked()) ret = FREE;
if(m_lineBtn.isChecked()) ret = LINE;
if(m_rectBtn.isChecked()) ret = RECT;
if(m_ellipseBtn.isChecked()) ret = ELLIPSE;
return ret;
}
Qt::GlobalColor Widget::drawColor()
{
Qt::GlobalColor ret = Qt::white;
switch (m_comboBox.currentIndex())
{
case 0x0:
ret = Qt::black;
break;
case 0x01:
ret = Qt::blue;
break;
case 0x02:
ret = Qt::green;
break;
case 0x03:
ret = Qt::red;
break;
case 0x04:
ret = Qt::yellow;
break;
default:
break;
}
return ret;
}
void Widget::mousePressEvent(QMouseEvent *event)
{
if(Qt::LeftButton == event->button())
{
m_curDrawPara.type = drawType();
m_curDrawPara.color = drawColor();
m_curDrawPara.points.append(event->pos());
qDebug() << m_curDrawPara.type;
qDebug() << m_curDrawPara.color;
}
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton)
{
append(event->pos());
update();
}
}
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
if(Qt::LeftButton == event->button())
{
append(event->pos());
m_stDrawParam.append(m_curDrawPara);
m_curDrawPara.type = NONE;
m_curDrawPara.color = Qt::white;
m_curDrawPara.points.clear();
update();
}
}
void Widget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
for(int i=0; i<m_stDrawParam.length(); i++)
{
draw(painter, m_stDrawParam[i]);
}
draw(painter, m_curDrawPara);
}
void Widget::draw(QPainter& painter, DrawParam& param)
{
if((NONE != param.type) && (param.points.length()>=2))
{
QPen pen;
int x = ( param.points[0].x() < param.points[1].x() ? param.points[0].x() : param.points[1].x() );
int y = ( param.points[0].y() < param.points[1].y() ? param.points[0].y() : param.points[1].y() );
int width = qAbs( param.points[0].x() - param.points[1].x() );
int height = qAbs( param.points[0].y() - param.points[1].y() );
pen.setColor(param.color);
painter.setPen(pen);
painter.setBrush(param.color);
switch (param.type)
{
case FREE:
for (int i=0; i<param.points.length()-1; i++)
{
painter.drawLine(param.points[i], param.points[i+1]);
}
break;
case LINE:
painter.drawLine(param.points[0], param.points[1]);
break;
case RECT:
painter.drawRect(x, y, width, height);
break;
case ELLIPSE:
painter.drawEllipse(x, y, width, height);
break;
default:
break;
}
}
}
void Widget::append(QPoint point)
{
if(NONE != m_curDrawPara.type)
{
if(FREE == m_curDrawPara.type)
{
m_curDrawPara.points.append(point);
}
else
{
if(2 == m_curDrawPara.points.length())
{
m_curDrawPara.points.removeLast();
}
m_curDrawPara.points.append(point);
}
}
}
工程链接:https://download.csdn.net/download/weixin_41937297/37918606