https://www.jianshu.com/p/5f20e2cd3ee0
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->setBackgroundRole(QPalette::Light);
this->setAutoFillBackground(true);
resize(400,360);
setWindowTitle("Rubber");
rubberBand = NULL;
}
Widget::~Widget()
{
}
// QPoint origin;
void Widget::mousePressEvent(QMouseEvent *e)
{
origin = e->pos();
if(!rubberBand){
rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
}
rubberBand->setGeometry(QRect(origin, QSize()));//设置了橡皮筋线的位置及大小
rubberBand->show();
}
void Widget::mouseMoveEvent(QMouseEvent *e)
{
if(rubberBand)
rubberBand->setGeometry(QRect(origin,e->pos()).normalized());
//normalized() 函数返回的也是一个QRect的对象,不过该对象的长和宽的值都是大于零时值
}
void Widget::mouseReleaseEvent(QMouseEvent *e)
{
// if(rubberBand)
// rubberBand->hide(); //当鼠标松开时,橡皮筋线就可以隐藏了
}