其他分享
首页 > 其他分享> > Qt 实现鼠标拖动控件

Qt 实现鼠标拖动控件

作者:互联网

    在QT项目中,窗口设置 setWindowFlags(Qt::FramelessWindowHint) 之后,就无法拖动;所以会自定义一个menubar控件,并实现窗口拖动;

效果如上图,上代码:

#include <QMainWindow>


class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

protected:
    bool eventFilter(QObject *, QEvent *);

private:
    QWidget *m_menu;
   
};

cpp:

#include "mainwindow.h"
#include <QMouseEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowFlags(Qt::FramelessWindowHint);
    this->setFixedSize(500,300);
    m_menu = new QWidget(this);
    m_menu->setFixedSize(this->width(), 50);
    m_menu->setStyleSheet("background-color:lightblue;");

    m_menu->installEventFilter(this);
}

MainWindow::~MainWindow()
{

}

bool MainWindow::eventFilter(QObject *watched, QEvent *eve)
{
    static QPoint mousePoint;
    static bool mousePressed = false;
    QMouseEvent *event = static_cast<QMouseEvent *>(eve);
    if(watched == m_menu)
    {
        if(event->type() == QEvent::MouseButtonPress)
        {
            if(event->button() == Qt::LeftButton)
            {
                mousePressed = true;
                mousePoint = event->globalPos() - this->pos();
                return true;
            }
        }
        else if(event->type() == QEvent::MouseButtonRelease)
        {
            mousePressed = false;
            return true;
        }
        else if(event->type() == QEvent::MouseMove)
        {
            this->move(event->globalPos() - mousePoint);
            return true;
        }
    }

    return QWidget::eventFilter(watched, eve);
}

 

两点注意:

1.m_menu->installEventFilter(this); 

本代码中,需要拖动的控件是自定义的m_menu,注册监测对象;

 

2.eventFilter;

在这个事件中,处理目标对象的事件;所以代码中先判断 (watched == m_menu);

 

原创,转载请注明出处;

标签:控件,QEvent,return,Qt,拖动,menu,MainWindow,QWidget,event
来源: https://blog.csdn.net/gz9456/article/details/110228988