Qt鼠标点中窗口任意位置不放,拖动窗口

主要是要重载三个鼠标事件

mainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include
#include

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void mousePressEvent(QMouseEvent *e);
void mouseMoveEvent(QMouseEvent *e);
void mouseReleaseEvent(QMouseEvent *e);
private:
Ui::MainWindow *ui;
QPushButton *btCloseBtn;
QPoint last;
};

#endif // MAINWINDOW_H

 

mainWindow.cpp

void MainWindow::mousePressEvent(QMouseEvent *e)

{

last = e->globalPos();

}

void MainWindow::mouseMoveEvent(QMouseEvent *e)

{

    int dx = e->globalX() - last.x();
    int dy = e->globalY() - last.y();
    last = e->globalPos();
    move(x() + dx, y() + dy);
}
void MainWindow::mouseReleaseEvent(QMouseEvent *e)
{
    int dx = e->globalX() - last.x();
    int dy = e->globalY() - last.y();
    move(x() + dx, y() + dy);
}
 

你可能感兴趣的:(Qt鼠标点中窗口任意位置不放,拖动窗口)