MainWindow.cpp
1 #include "mainwindow.h"
2 #include "ui_mainwindow.h"
3
4 MainWindow::MainWindow(QWidget *parent) :
5 QMainWindow(parent),
6 ui(new Ui::MainWindow)
7 {
8 ui->setupUi(this);
9
10 setWindowFlags(Qt::FramelessWindowHint);
11 m_bMouseLftBtnPressed = false;
12 }
13
14 MainWindow::~MainWindow()
15 {
16 delete ui;
17 }
18
19 /*---------------------------------------------------------------------------
20 函数名:mouseMoveEvent
21 功能:鼠标移动事件函数,在该函数内实现对窗口的拖动功能
22 只有在鼠标左键按下的情况下才能对窗口进行拖动
23 ---------------------------------------------------------------------------*/
24 void MainWindow::mouseMoveEvent(QMouseEvent *event)
25 {
26 if (this->isMaximized()) // 如果当前是最大化,则不允许移动
27 return;
28
29 if ((event->buttons() & Qt::LeftButton) && m_bMouseLftBtnPressed) // 是否按下鼠标左键
30 {
31 QPoint ptTemp = event->globalPos(); // 当前鼠标全局位置
32 ptTemp = ptTemp - m_ptMouseLatestPos; // 计算移动变量
33 ptTemp = ptTemp + pos(); // 窗口原始位置(pos()) + 鼠标移动变量(ptemp) = 最终窗口位置
34 move(ptTemp); // 移动窗口到新的位置
35
36 m_ptMouseLatestPos = event->globalPos(); // 记录当前鼠标按下的位置
37 }
38 }
39
40
41 /*---------------------------------------------------------------------------
42 函数名:mousePressEvent
43 功能:鼠标按键按下事件函数,在函数内判断是否可以拖动该窗口
44 只有在标题栏区域内按下鼠标左键才可以拖动当前窗口
45 ---------------------------------------------------------------------------*/
46 void MainWindow::mousePressEvent(QMouseEvent *event)
47 {
48 this->setFocus();
49
50 // 只有在标题栏区域内按下鼠标左键且当前窗口不是最大化的情况下才可以拖动
51 if (Qt::LeftButton == event->button() && 0 == (Qt::WindowMaximized & this->windowState()))
52 {
53 // 只有在标题栏区域内按下鼠标左键才可以进行拖动操作
54 if (ui->TitleWidget->geometry().contains(event->pos()))
55 {
56 m_ptMouseLatestPos = event->globalPos(); // 记录鼠标按下的位置
57 m_bMouseLftBtnPressed = true; // 标记鼠标为按下状态
58 event->ignore();
59 }
60 }
61 }
62
63
64 /*---------------------------------------------------------------------------
65 函数名:mouseReleaseEvent
66 功能:鼠标按键抬起事件函数,在该函数内将取消窗口的可拖动操作
67 只有鼠标左键抬起的情况下才认为要结束拖动
68 ---------------------------------------------------------------------------*/
69 void MainWindow::mouseReleaseEvent(QMouseEvent *event)
70 {
71 if (Qt::LeftButton == event->button())
72 {
73 m_bMouseLftBtnPressed = false;
74 }
75 }
MainWindow.h
1 #include <QMainWindow>
2
3 namespace Ui {
4 class MainWindow;
5 }
6
7 class MainWindow : public QMainWindow
8 {
9 Q_OBJECT
10
11 public:
12 explicit MainWindow(QWidget *parent = 0);
13 ~MainWindow();
14 protected:
15 // 鼠标移动事件函数
16 void mouseMoveEvent(QMouseEvent *event);
17
18 // 鼠标按键按下事件函数
19 void mousePressEvent(QMouseEvent *event);
20
21 // 鼠标按键抬起事件函数
22 void mouseReleaseEvent(QMouseEvent *event);
23
24 private:
25 Ui::MainWindow *ui;
26 QPoint m_ptMouseLatestPos; // 鼠标的最后位置
27 bool m_bMouseLftBtnPressed; // 标识当前是否按下鼠标左键
28
29 };
需要自己拖一个窗口上去