[QT]自定义标题栏可移动实现(已验证,直接套用到自己代码中即可)

代码片段:
*.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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值