Qt实现无标题无边窗口的整体 拖拽 功能

  在没有标题栏和边框的情况下想拖动窗体,如果不单独处理是不能拖动的,想实现这个拖动功能其实很简单,只需要重写以下三个鼠标函数即可:

mousePressEvent、mouseMoveEvent、mouseReleaseEvent。

 1 window.h头文件:
 2 
 3 #ifndef _WINDOW_H
 4 #define _WINDOW_H
 5 
 6 #include <QMainWindow>
 7 #include <QApplication>
 8 #include <QMouseEvent>
 9 
10 namespace Ui {
11 class Window;
12 }
13 
14 class Window : public QMainWindow
15 {
16     Q_OBJECT
17 
18 public:
19     explicit Window (QWidget* parent = 0);
20     ~Window();
21 
22 protected:
23     void mousePressEvent(QMouseEvent *event);
24     void mouseMoveEvent(QMouseEvent *event);
25     void mouseReleaseEvent(QMouseEvent *event);
26 
27 private:
28     Ui::Window* m_ui;
29 
30     bool m_move;
31     QPoint m_startPoint;
32     QPoint m_windowPoint;
33 
34 };
35 
36 #endif
window.cpp文件:


#include "Window.h" #include "ui_Window.h" Window::Window (QWidget* parent) : QMainWindow (parent) { m_ui = new Ui::Window; m_ui->setupUi (this); /*设置无边、无标题栏窗口*/ this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint); /*给是否移动的标志初始化为false*/ m_move = false; } Window::~Window() { delete m_ui; } void Window::mousePressEvent(QMouseEvent *event) { /*当鼠标左键点击时.*/ if (event->button() == Qt::LeftButton) { m_move = true; /*记录鼠标的世界坐标.*/ m_startPoint = event->globalPos(); /*记录窗体的世界坐标.*/ m_windowPoint = this->frameGeometry().topLeft(); } } void Window::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { /*移动中的鼠标位置相对于初始位置的相对位置.*/ QPoint relativePos = event->globalPos() - m_startPoint; /*然后移动窗体即可.*/ this->move(m_windowPoint + relativePos ); } } void Window::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { /*改变移动状态.*/ m_move = false; } }

 

posted @ 2019-09-18 15:22  YJCCN  阅读(1235)  评论(0编辑  收藏  举报