用label显示图片,现在需要在图片上绘制一个矩形并能用鼠标进行拖动,所以重写了窗口的paintEvent函数:
void Temperature_M::paintEvent(QPaintEvent*)思路就是在图片上绘制矩形,再把图片显示。
{
QPainter paint(&img);
paint.setPen(QPen(Qt::green,5));
paint.drawRect(rect1_x,rect1_y,rect1_width,rect1_height);//rect1_x,rect1_y,rect1_width,rect1_height分别是矩形的起点和宽和高
picture->setPixmap(QPixmap::fromImage(img));
}
接下来就是关于重写鼠标事件的函数
void Temperature_M:: mousePressEvent(QMouseEvent*mouse_event)拖动矩形框输出的效果却是这样的
{
if(mouse_event->button()==Qt::LeftButton)//鼠标左键按下
{
QPoint pos=mouse_event->pos();
if(pos.x()>rect1_x&&pos.y()>rect1_y&&pos.x()<(rect1_x+rect1_width)&&pos.y()<(rect1_y+rect1_height))//在矩形区域内
rect1_drag=true;
}
}
void Temperature_M:: mouseMoveEvent(QMouseEvent*mouse_event)
{
if(rect1_drag)
{
rect1_x=mouse_event->pos().x();//获取当前的x
rect1_y=mouse_event->pos().y();//获取当前y
}
}
void Temperature_M:: mouseReleaseEvent(QMouseEvent*mouse_event)
{
rect1_drag=false;
update();
}

------解决方案--------------------
在每次绘制之前将picture重置,擦出上次绘制内容
------解决方案--------------------
看下我博客帖子。。http://blog.csdn.net/kfbyj/article/details/8811010
------解决方案--------------------
paintEvent在每次鼠标有动作的时候都会重新绘制一遍,加个if条件,不满足就不绘制框框
------解决方案--------------------
因为你每次都画了一个矩形到img上,当然是擦不掉的。
这个矩形可以考虑不要画到img上,直接画到窗口上就可以了。