qt 窗口可拖动

参考:https://blog.csdn.net/qq_45254369/article/details/125878621

左键按住,拖动窗口

头文件:

#ifndef FRAME_H
#define FRAME_H

#include <QFrame>

namespace Ui {
class Frame;
}

class Frame : public QFrame
{
    Q_OBJECT

public:
    explicit Frame(QWidget *parent = nullptr);
    ~Frame();

protected:
    virtual void mouseMoveEvent(QMouseEvent *event);
    virtual void mousePressEvent(QMouseEvent *event);
    virtual void mouseReleaseEvent(QMouseEvent *event);
  bool m_bPressed;//是否在窗口点击鼠标左键(非点击到窗口按钮上),解决按住按钮后,移动到按钮外时,窗口会乱飘的问题
    QPoint z; 
private: 
    Ui::Frame *ui; 
}; 

#endif // FRAME_H

源文件:

#include "frame.h"
#include "ui_frame.h"
#include <QMouseEvent>

Frame::Frame(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::Frame)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
    m_bPressed = false;
}

Frame::~Frame()
{
    delete ui;
}

void Frame::mouseMoveEvent(QMouseEvent *event)
{
    if(!m_bPressed){
        return;
    }
    QWidget::mouseMoveEvent(event);

    QPoint y = event->globalPos(); // 鼠标相对于桌面左上角位置
    QPoint x = y - this->z;

    this->move(x);
}

void Frame::mousePressEvent(QMouseEvent *event)
{
    m_bPressed = true;
    QWidget::mousePressEvent(event);

    QPoint x = this->geometry().topLeft(); // 窗口左上角相对于桌面左上角位置
    QPoint y = event->globalPos(); // 鼠标相对于桌面左上角位置
    this->z = y - x; // 这是个定值
}

void Frame::mouseReleaseEvent(QMouseEvent *event)
{
    m_bPressed = false;
    QWidget::mouseReleaseEvent(event);

    this->z = QPoint();
}

ui文件:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Frame</class>
 <widget class="QFrame" name="Frame">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Frame</string>
  </property>
  <property name="styleSheet">
   <string notr="true">background-color: rgb(0, 255, 255);</string>
  </property>
  <property name="frameShape">
   <enum>QFrame::StyledPanel</enum>
  </property>
  <property name="frameShadow">
   <enum>QFrame::Raised</enum>
  </property>
 </widget>
 <resources/>
 <connections/>
</ui>

调用方法:

void MainWindow::on_btnFrameless_clicked()
{
    Frame* frame = new Frame(this);
    frame->show();
}

 

posted @ 2022-12-06 11:13  阳光下的小土豆  阅读(453)  评论(0编辑  收藏  举报