Qt 窗口随鼠标移动效果

实现在窗口任意位置按下鼠标左键都可以移动窗口的效果,完整代码如下:

mainwindow.h:

cpp 复制代码
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMouseEvent>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
protected:
    // 重写父类鼠标点击事件:鼠标按下的时候记录偏移量,方便鼠标移动时使用
    void mousePressEvent(QMouseEvent *event) override;
    // 重写父类鼠标移动事件
    void mouseMoveEvent(QMouseEvent *event) override;
private:
    Ui::MainWindow *ui;
    QPoint m_offset;// 窗口移动时,鼠标点击位置和窗口左上角的偏移量
};
#endif // MAINWINDOW_H

mainwindow.cpp:

cpp 复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
// 重写父类鼠标点击事件:鼠标按下的时候记录偏移量,方便鼠标移动时使用
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    // event->globalPos():鼠标点击位置和桌面左上角的距离
    // this->pos():窗口左上角位置和桌面左上角位置的距离
    m_offset = event->globalPos() - this->pos();
}
// 重写父类鼠标移动事件
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    // this->move():设置窗口左上角的位置
    // event->globalPos():鼠标点击位置和桌面左上角的距离
    this->move(event->globalPos() - m_offset);
}
相关推荐
li星野8 小时前
C++/Qt 开发避坑与重构原则清单 (速记版)
c++·qt·重构
沫璃染墨9 小时前
《Qt从零入门系列(十七):网络编程基础详解——从Socket原理到TCP/UDP通信API》
开发语言·网络·c++·qt·http·qt5·qt6.3
ShineWinsu9 小时前
对于Qt:绘图的解析
开发语言·数据库·c++·qt·面试·客户端·绘图
潇湘散客11 小时前
PlantAis插件更新:RVM负实体开关;VUE文件读取与导出等
c++·qt·opengl
richard_yuu1 天前
图像融合与多帧平均提SNR
qt·opencv·计算机视觉
ShineWinsu1 天前
对于Qt:QSS样式属性的解析
开发语言·c++·qt·面试·盒子模型·客户端·qss
小灰灰搞电子2 天前
Qt 输入验证入门:QValidator 类详解
开发语言·qt
凤年徐2 天前
Qt 第三章 常用控件总结
开发语言·qt
草莓熊Lotso2 天前
Qt 进阶控件实战:下拉框、列表、表格 + 旋钮 / 滑动条全攻略
大数据·c语言·开发语言·c++·人工智能·qt
迎風吹頭髮2 天前
QT中使用QSqlTableModel快速展示SQLite3数据表(TableView实现)
开发语言·qt·sqlite