1、widget.h文件
#ifndef WIDGET_H #define WIDGET_H #include <QWidget>//注意我使用的是Qt5,Qt4与Qt5的区别可以参考http://qt-project.org/wiki/Transition_from_Qt_4.x_to_Qt5 #include<QMouseEvent> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); QPoint move_point; //移动的距离 bool mouse_press; //鼠标按下 //鼠标按下事件 void mousePressEvent(QMouseEvent *event); //鼠标释放事件 void mouseReleaseEvent(QMouseEvent *event); //鼠标移动事件 void mouseMoveEvent(QMouseEvent *event); private: Ui::Widget *ui; }; #endif // WIDGET_H2、widget.cpp文件
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); this->setMouseTracking(false); setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);//设置主窗口无边框 } Widget::~Widget() { delete ui; } void Widget::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton) { this->setMouseTracking(true); mouse_press = true; //鼠标相对于窗体的位置(或者使用event->globalPos() - this->pos()) move_point = event->pos();; } } void Widget::mouseReleaseEvent(QMouseEvent *event) { //设置鼠标为未被按下 mouse_press = false; } void Widget::mouseMoveEvent(QMouseEvent *event) { //若鼠标左键被按下 // qDebug()<<"mouse_press="<<event->globalPos(); if(mouse_press) { //鼠标相对于屏幕的位置 QPoint move_pos = event->globalPos(); //移动主窗体位置 this->move(move_pos - move_point); } }
原文地址:http://blog.csdn.net/tengweitw/article/details/38817595