QT界面开发-(特效)整体可拖动的窗口

转载自邵发《C/C++系列教程》Qt界面开发 https://chuanke.baidu.com/v4509752-209060-1284517.html

只有顶部一小条可以拖动

 1 private:
 2     virtual void mouseMoveEvent(QMouseEvent * event);
 3     virtual void mousePressEvent(QMouseEvent * event);
 4     virtual void mouseReleaseEvent(QMouseEvent * event);
 5 
 6     bool m_dragging; // 是否正在拖动
 7     QPoint m_startPosition; // 拖动开始前的鼠标位置
 8     QPoint m_framePosition; // 窗体的原始位置
 9 
10 
11 //写到ui.setupUi(this);下面
12     m_dragging = false;
13 
14     // 不显示标题栏(亦无边框)
15     setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
16 
17 
18 
19 void TestAandB::mousePressEvent(QMouseEvent *event)
20 {
21     // 只响应左键
22     if (event->button() == Qt::LeftButton)
23     {
24         QRect titleRect = rect();
25         titleRect.setBottom(titleRect.top() + 80);
26 
27         if (titleRect.contains(event->pos()))
28         {
29             m_dragging = true;
30             m_startPosition = event->globalPos();
31             m_framePosition = frameGeometry().topLeft();
32         }
33     }
34 
35     QWidget::mousePressEvent(event);
36 }
37 
38 void TestAandB::mouseMoveEvent(QMouseEvent *event)
39 {
40     // 只响应左键
41     if (event->buttons() & Qt::LeftButton)
42     {
43         if (m_dragging)
44         {
45             // delta 相对偏移量, 
46             QPoint delta = event->globalPos() - m_startPosition;
47 
48             // 新位置:窗体原始位置  + 偏移量
49             move(m_framePosition + delta);
50         }
51     }
52 
53     QWidget::mouseMoveEvent(event);
54 }
55 
56 void TestAandB::mouseReleaseEvent(QMouseEvent * event)
57 {
58     m_dragging = false;
59     QWidget::mouseReleaseEvent(event);
60 }

全部可以拖动

 1 void QTXiDaoPanJieMian1::mousePressEvent(QMouseEvent *event)
 2 {
 3     // 只响应左键
 4     if (event->button() == Qt::LeftButton)
 5     {
 6         m_dragging = true;
 7         m_startPosition = event->globalPos();
 8         m_framePosition = frameGeometry().topLeft();
 9     }
10     QWidget::mousePressEvent(event);
11 }
12 
13 void QTXiDaoPanJieMian1::mouseMoveEvent(QMouseEvent *event)
14 {
15     // 只响应左键
16     if (event->buttons() & Qt::LeftButton)
17     {
18         if (m_dragging)
19         {
20             // delta 相对偏移量, 
21             QPoint delta = event->globalPos() - m_startPosition;
22 
23             // 新位置:窗体原始位置  + 偏移量
24             move(m_framePosition + delta);
25         }
26     }
27     QWidget::mouseMoveEvent(event);
28 }
29 
30 void QTXiDaoPanJieMian1::mouseReleaseEvent(QMouseEvent * event)
31 {
32     // 结束dragging
33     m_dragging = false;
34     QWidget::mouseReleaseEvent(event);
35 }
原文地址:https://www.cnblogs.com/nxopen2018/p/12176486.html