代码片段:
*.h
protected:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
*.cpp
#define BTNSIZE 35
Test::Test(QDialog parent) :
QDialog(parent),
ui(new Ui::Test)
{
ui->setupUi(this);
QDesktopWidget desktop = QApplication::desktop();
m_availableWindRect = QRect(desktop->availableGeometry());
}
void Test::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_mousePressed = false;
}
event->ignore();
setCursor(Qt::ArrowCursor);
QWidget::mouseReleaseEvent(event);
}
void Test::mousePressEvent(QMouseEvent *event)
{
setFocus();
if (event->button() == Qt::LeftButton)
{
m_offset = event->pos();
//鼠标在标题栏区域 QRect ( int left, int top, int width, int height )
if(QRect(0,0,width()-120,BTNSIZE).contains(event->pos()))
{
m_mousePressed = true;
}
}
QWidget::mousePressEvent(event);
}
void Test::mouseMoveEvent(QMouseEvent *event)
{
if (m_mousePressed)
{
// //以下是防止窗口拖出可见范围外
QRect widgetRect(this->geometry());
QPoint point(event->globalPos() - m_offset);
//左移
int x1 = this->width() - BTNSIZE;//窗口宽度 - BTNSIZE
if (abs(point.x()) >= x1 && point.x()<=0)//
{
point = QPoint(-abs(x1),point.y());
}
//下移
int y = m_availableWindRect.bottomRight().y() - BTNSIZE;
if (point.y() >= y && widgetRect.topLeft().y() >= y)
{
point = QPoint(point.x(),y);
}
//上移
if (point.y() <= 0)
{
point = QPoint(point.x(),0);
}
//右移
int x = m_availableWindRect.bottomRight().x() - BTNSIZE;
if (point.x() >= x && widgetRect.topLeft().x() >= x)
{
point = QPoint(x,point.y());
}
move(point);
}
QWidget::mouseMoveEvent(event);
}