窗口拖拽移动

发布时间:2024年01月12日
#ifndef BASEWIDGET_H
#define BASEWIDGET_H

#include <QWidget>
#include <QMouseEvent>
#include <QMouseEvent>
#include <QDesktopWidget>

class BaseWidget : public QWidget
{
    Q_OBJECT
public:
    explicit BaseWidget(QWidget *parent = 0);

signals:

protected:
    void paintEvent(QPaintEvent *);
    bool eventFilter(QObject *watched, QEvent *event);
    void showEvent(QShowEvent *event);

private:
    bool m_bMousePressed;
    QPoint m_hotSpot;
};

#endif // BASEWIDGET_H
#include "basewidget.h"
#include <QPushButton>
#include <QPainter>
#include <QStyleOption>
const int titleH = 45;
BaseWidget::BaseWidget(QWidget *parent)
    : QWidget(parent)
{
    installEventFilter(this);
    setWindowFlags(Qt::FramelessWindowHint);
	setAttribute(Qt::WA_Hover);
}

bool BaseWidget::eventFilter(QObject *watched, QEvent *event)
{
    switch (event->type())
    {
    case QEvent::MouseButtonPress:
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if (mouseEvent->button() == Qt::LeftButton && mouseEvent->pos().y()<titleH)
        {
            m_bMousePressed = true;
            m_hotSpot = mouseEvent->pos();
        }
    }
        break;
    case QEvent::MouseMove:
    {
        if (m_bMousePressed)
			move(QCursor::pos() - m_hotSpot);
    }
        break;
    case QEvent::MouseButtonRelease:
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if (mouseEvent->button() == Qt::LeftButton) m_bMousePressed = false;
    }
        break;
    default:
        break;
    }
    return QWidget::eventFilter(watched, event);
}

void BaseWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void BaseWidget::showEvent(QShowEvent *event)
{
	setAttribute(Qt::WA_Mapped);
	QWidget::showEvent(event);
}

文章来源:https://blog.csdn.net/xiaoyao_zhang/article/details/135551205
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。