蓝色星晨|C/C++编程笔记:无边框窗口橡皮筋拉伸效果( 二 )

功能代码实现为了便于通用其他项目 , 我将功能代码封装成另一个类 , 派生于QWidget , 处理鼠标事件、窗口大小改变事件及对区域与橡皮筋的操作 。 代码实现如下:
class CFrameForm : public QWidget{Q_OBJECTpublic:enum Type { LeftTop=0, Top, RightTop, Right, RightBottom, Bottom, LeftBottom, Left, Other };explicit CFrameForm(QWidget*parent=0);~CFrameForm();void setType(int type) {m_type = (Type)type;}void setCanResize(bool c);private slots:void setHandel(QWidget *handel, CFrameForm::Type type);private:void mousePressEvent(QMouseEvent *);void mouseMoveEvent(QMouseEvent *);void mouseReleaseEvent(QMouseEvent *);void showEvent(QShowEvent *event);void resizeEvent(QResizeEvent *e);private:QPoint m_pos;QRect m_normalRect;QDesktopWidget m_desk;QWidget* m_parent;Type m_type;CRubberBand m_rubber;// 橡皮筋QListm_handles;// 8块区域};类功能实现如下:
const int iresize = 8;// 拖拽窗体尺寸像素CFrameForm::CFrameForm(QWidget*parent) :QWidget(parent), m_parent(parent){m_rubber.hide();m_type = Other;setWindowFlags(windowFlags() | Qt::FramelessWindowHint);// 设置成无边框for (int i = Left; i >= LeftTop; i--)// 创建8个区域{CHandel *w = new CHandel(i, this);m_handles.push_front(w);}}CFrameForm::~CFrameForm(){m_rubber.clear();}void CFrameForm::setCanResize(bool c)// 设置是否可以进行拖拽拉伸{for (int i = 0; i < m_handles.size(); i++){setHandel(m_handles[i], !c ? Other : (Type)m_handles[i]->type());m_handles[i]->raise();}}// 根据所属类型 , 移动到对应区域和设置对应光标void CFrameForm::setHandel(QWidget*handel, CFrameForm::Type type){switch (type){case LeftTop:handel->setGeometry(QRect(0,0,10,10));handel->setCursor(Qt::SizeFDiagCursor);break;case Top:handel->setGeometry(QRect(10,0,width()-20,iresize));handel->setCursor(Qt::SizeVerCursor);break;case RightTop:handel->setGeometry(QRect(width()-10,0,10,10));handel->setCursor(Qt::SizeBDiagCursor);break;case Right:handel->setGeometry(QRect(width()-iresize,10,iresize,height()-20));handel->setCursor(Qt::SizeHorCursor);break;case RightBottom:handel->setGeometry(QRect(width()-10,height()-10,10,10));handel->setCursor(Qt::SizeFDiagCursor);break;case Bottom:handel->setGeometry(QRect(10,height()-iresize,width()-20,iresize));handel->setCursor(Qt::SizeVerCursor);break;case LeftBottom:handel->setGeometry(QRect(0,height()-10,10,10));handel->setCursor(Qt::SizeBDiagCursor);break;case Left:handel->setGeometry(QRect(0,10,iresize,height()-20));handel->setCursor(Qt::SizeHorCursor);break;case Other:handel->setCursor(Qt::ArrowCursor);break;}}void CFrameForm::mousePressEvent(QMouseEvent *e)// 判断鼠标按键与类型正确与否{if ((e->button() == Qt::LeftButton)elseQWidget::mousePressEvent(e);}void CFrameForm::mouseMoveEvent(QMouseEvent *e) // 动态计算大小拉伸区域大小 , 并设置显示橡皮筋{if (!m_pos.isNull()){QWidget *p = m_parent;if (pint w = p->minimumSizeHint().width();int h = p->minimumSizeHint().height();if (m_type == Right) {r = QRect(p->pos(), QSize(e->pos().x(), height()));if (r.width() < w)r.setWidth(w);}else if (m_type == Left) {int x = QCursor::pos().x();r = QRect(x, p->pos().y(), p->pos().x() + width() - x, height());int dx = r.x() + r.width();if (r.width()