其他分享
首页 > 其他分享> > Qt——自定义标题栏——重写标题栏和鼠标事件,移动窗口

Qt——自定义标题栏——重写标题栏和鼠标事件,移动窗口

作者:互联网

头文件加入这两句:

#include <QPoint>  //坐标点
#include <QMouseEvent> //鼠标事件

public:
    // 移动窗口的变量;
    bool m_isPressed; //鼠标按下标志
    QPoint m_startMovePos;  //开始移动的坐标点
protected:

    void mouseMoveEvent(QMouseEvent* event);
    void mousePressEvent(QMouseEvent* event);
    void mouseReleaseEvent(QMouseEvent* event);

 

源文件实现:

DefinedTitleBar::DefinedTitleBar(QWidget* parent)
    : QWidget(parent)
    , m_isPressed(false)  //初始化鼠标按下标志为 false

{

}

 void DefinedTitleBar::mouseMoveEvent(QMouseEvent* event)   //鼠标移动事件
 {
     if (m_isPressed) //判断鼠标是否按下
     {
         QPoint movePoint = event->globalPos() - m_startMovePos;  //鼠标按下的坐标
         QPoint widgetPos = this->pos();
         m_startMovePos = event->globalPos();
        this->move(widgetPos.x() + movePoint.x(), widgetPos.y() + movePoint.y()); 
     }

 }

 void DefinedTitleBar::mousePressEvent(QMouseEvent* event)  //鼠标按下事件
 {
     QPoint _mouseCurrent_software = event->pos(); //获取鼠标相对于软件的坐标
     QPoint _mouseCurrent_windows = event->globalPos(); //获取鼠标相对于桌面的坐标

     int _titleBar_width = ui.widget_titleBar->width();  //标题栏的宽度
     int _titleBar_height = ui.widget_titleBar->height(); //标题栏的高度
     if (!isMaximized())
     {    
         //判断鼠标是否在标题栏范围内,如果在标题栏附近才能移动(标题栏 是拖到ui界面的 QFrame)
         if (_mouseCurrent_software.x()<= _titleBar_width&&_mouseCurrent_software.y()<=_titleBar_height)   
         {
             m_isPressed = true;
             m_startMovePos = event->globalPos();
         }
         else
         {
             m_isPressed = false;
         }
         
     }
    
 }



 void DefinedTitleBar::mouseReleaseEvent(QMouseEvent* event)  //鼠标释放事件
 {
     m_isPressed = false;
     qDebug() << QString::fromLocal8Bit("鼠标释放:") << endl
         <<endl << QString::fromLocal8Bit("鼠标相对于软件的坐标是:")  
         <<"(" << event->pos() << ")" << endl;    //pos 相对于软件


     qDebug() << QString::fromLocal8Bit("鼠标相对于桌面的坐标是:") 
         << "(" << event->globalPos() << ")"   //globalPos 相对于桌面

         << endl<<endl<<endl<<endl;
     
 }

 

标签:Qt,自定义,void,标题栏,QMouseEvent,QPoint,event,鼠标
来源: https://www.cnblogs.com/RedWetPlace/p/16533428.html