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);
}
相关推荐
blasit9 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
范特西.i5 天前
QT聊天项目(8)
开发语言·qt
枫叶丹46 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
十五年专注C++开发6 天前
Qt deleteLater作用及源码分析
开发语言·c++·qt·qobject
kangzerun6 天前
SQLiteManager:一个优雅的Qt SQLite数据库操作类
数据库·qt·sqlite
金刚狼886 天前
qt和qt creator的下载安装
开发语言·qt
追烽少年x6 天前
Qt中使用Zint库显示二维码
qt
谁刺我心6 天前
qt源码、qt在线安装器镜像下载
开发语言·qt
金刚狼886 天前
在qt creator中创建helloworld程序并构建
开发语言·qt
扶尔魔ocy6 天前
【转载】QT使用linuxdeployqt打包
开发语言·qt