【Qt】自定义标题栏并实现鼠标拖拽移动

来源:互联网 发布:打开telnet端口命令 编辑:程序博客网 时间:2024/05/21 00:49

1.Qt在windows下变成,标题栏归系统管理器管理。想要自定义就只能把原来的隐藏掉,然后自己添加组件,自己做;

2.首先设置属性,隐藏掉原来的标题栏: 

    /* 标题栏样式 */    this->setWindowFlags(Qt::FramelessWindowHint |                         Qt::WindowSystemMenuHint |                         Qt::WindowMinMaxButtonsHint);
3.重写鼠标的三个事件,分别是:

    /* custom title bar */    void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;    void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE;    void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
4.代码如下:

void MainWindow::mousePressEvent(QMouseEvent *event){    if( event->button() == Qt::LeftButton &&            ui->frame_title_bar->frameRect().contains(event->globalPos() - this->frameGeometry().topLeft())){        m_Press = event->globalPos();        leftBtnClk = true;    }    event->ignore();//表示继续向下传递事件,其他的控件还可以去获取}void MainWindow::mouseReleaseEvent(QMouseEvent *event){    if( event->button() == Qt::LeftButton ){        leftBtnClk = false;    }    event->ignore();}void MainWindow::mouseMoveEvent(QMouseEvent *event){    if( leftBtnClk ){        m_Move = event->globalPos();        this->move( this->pos() + m_Move - m_Press );        m_Press = m_Move;    }    event->ignore();}
5.注意事项:

1)通过frame.frameRect().contains 可以判断鼠标位置是否在自定义的标题栏上;但是这里传入的位置是以MainWindow的左上角为原点的;

所以使用的是 

event->globalPos() - this->frameGeometry().topLeft()
来得到该坐标;

2)窗口移动直接使用move() ; 里面参数是:

this->pos() + m_Move - m_Press
逻辑上也很好理解,现在的窗口位置 + (  鼠标现在位置 -  鼠标原来位置 ); 不要忘记去更新鼠标的原来位置 m_Press = m_Move;

3) 最后的 event->ignore(); 保证该鼠标事件可以继续传递下去,以便其他控件可以继续处理。因为标题栏是在主窗口上面的,所以event会先传给标题栏,然后如果没有被接受才会传给主窗口。





1 0
原创粉丝点击