最简单的可拖动对话框(大小不可改变)
cpp
#ifndef DIALOG_H
#define DIALOG_H
/**
* @file dialog.h
* @author lpl
* @brief 无边框dialog类
* @date 2024/06/05
*/
#include <QDialog>
#include <QMouseEvent>
namespace Ui {
class Dialog;
}
/**
* @brief The Dialog class
* 无边框dialog
*/
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
/**
* @brief mousePressEvent 鼠标点击事件
* @param ev 鼠标事件
*/
virtual void mousePressEvent(QMouseEvent *ev) override;
/**
* @brief mouseMoveEvent 鼠标移动事件
* @param ev 鼠标事件
*/
virtual void mouseMoveEvent(QMouseEvent *ev) override;
/**
* @brief mouseReleaseEvent 鼠标释放事件
* @param ev 鼠标事件
*/
virtual void mouseReleaseEvent(QMouseEvent *ev) override;
private:
Ui::Dialog *ui;
bool m_bIsPress; ///< 是否点击鼠标
QPoint m_pointMoveDis; ///< 鼠标与电脑窗体左上角的相对位置
};
#endif // DIALOG_H
cpp
#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
#include <QMouseEvent>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::mousePressEvent(QMouseEvent *ev)
{
qDebug()<<ev->globalPos();
//按下鼠标左键
if(Qt::LeftButton == ev->button()){
m_pointMoveDis = ev->globalPos();
m_bIsPress = true;
}
QDialog::mousePressEvent(ev);
}
void Dialog::mouseMoveEvent(QMouseEvent *ev)
{
if (ev->buttons() & Qt::LeftButton)
{
if(m_bIsPress)
{
QPoint movePos = ev->globalPos();
this->move(this->pos() + movePos - m_pointMoveDis);
m_pointMoveDis = movePos;
}
}
QDialog::mouseMoveEvent(ev);
}
void Dialog::mouseReleaseEvent(QMouseEvent *ev)
{
if(Qt::LeftButton == ev->button())
{
m_bIsPress = false;
}
QDialog::mouseReleaseEvent(ev);
}