// 头文件 #ifndef TITLEBAR_H #define TITLEBAR_H #include <QWidget> #include <QPoint> //坐标点 #include <QMouseEvent> //鼠标事件 class TitleBar : public QWidget { Q_OBJECT public: explicit TitleBar(QWidget *parent = nullptr); // 移动窗口的变量; bool m_isPressed; //鼠标按下标志 QPoint m_startMovePos; //开始移动的坐标点 protected: void mouseMoveEvent(QMouseEvent* event); void mousePressEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); signals: private: QWidget* m_parent; }; #endif // TITLEBAR_H
// 源文件 #include "titlebar.h" #include <qDebug> TitleBar::TitleBar(QWidget* parent) : QWidget(parent) , m_isPressed(false) //初始化鼠标按下标志为 false , m_parent(parent) { // 设置唯一标识符 this->setObjectName("TitleBar"); // 拥有子窗口自己的样式 setAttribute(Qt::WA_StyledBackground); } //鼠标移动事件 void TitleBar::mouseMoveEvent(QMouseEvent* event) { //判断鼠标是否按下 if (m_isPressed) { QPoint movePoint = event->globalPos() - m_startMovePos; QPoint widgetPos = m_parent->pos(); m_startMovePos = event->globalPos(); if(m_parent) { m_parent->move(widgetPos.x() + movePoint.x(), widgetPos.y() + movePoint.y()); } } } //鼠标按下事件 void TitleBar::mousePressEvent(QMouseEvent* event) { //获取鼠标相对于软件的坐标 QPoint _mouseCurrent_software = event->pos(); //获取鼠标相对于桌面的坐标 QPoint _mouseCurrent_windows = event->globalPos(); //标题栏的宽度 int _titleBar_width = this->width(); //标题栏的高度 int _titleBar_height = this->height(); if (!isMaximized()) { //判断鼠标是否在标题栏范围内 if (_mouseCurrent_software.x()<= _titleBar_width&&_mouseCurrent_software.y()<=_titleBar_height) { m_isPressed = true; m_startMovePos = event->globalPos(); } else { m_isPressed = false; } } } //鼠标释放事件 void TitleBar::mouseReleaseEvent(QMouseEvent* event) { m_isPressed = false; }
// 使用 #include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QWidget(parent) , m_titleBar(new TitleBar(this)) { // 去掉标题栏和边框 setWindowFlags(Qt::Window | Qt::FramelessWindowHint); m_titleBar->show(); } MainWindow::~MainWindow() {}
效果: 鼠标左键按住移动,跟随鼠标移动。
标签:qt,parent,鼠标,标题栏,TitleBar,QWidget,include,event,自定义 From: https://www.cnblogs.com/RedWetPlace/p/18013605