实现在一个窗口内随意拖动一个控件功能
#ifndef MYDRAGWIDGET_H
#define MYDRAGWIDGET_H
#include <QWidget>
class MyDragWidget : public QWidget
{
Q_OBJECT
public:
explicit MyDragWidget(PointInfo ptInfo,QWidget *parent = nullptr);
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
signals:
public slots:
private:
void user_drag_out_disposal();
private:
QPoint m_mouse_point;
QPoint m_widget_point;
bool m_bMove;
private:
QWidget* m_Parent;
};
#endif // MYDRAGWIDGET_H
#include "MyDragWidget.h"
#include <QMouseEvent>
#include <QVBoxLayout>
MyDragWidget::MyDragWidget(PointInfo ptInfo, QWidget *parent) : QWidget(parent)/*, m_point_info(ptInfo)*/
{
if(parent)
m_Parent = parent;
m_bMove = false;
}
void MyDragWidget::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_bMove = true;
m_mouse_point = event->globalPos(); // 鼠标世界坐标
m_widget_point = this->frameGeometry().topLeft(); // 窗口世界坐标
}
}
void MyDragWidget::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton)
{
QPoint pt = event->globalPos() - m_mouse_point;
this->move(m_widget_point + pt);
user_drag_out_disposal();
}
}
void MyDragWidget::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
m_bMove = false;
}
void MyDragWidget::user_drag_out_disposal()
{
int width = m_Parent->width() - this->width();
int height = m_Parent->height() - this->height();
int x = this->x();
int y = this->y();
if(m_Parent)
{
if(x <= 0)
{
if(y <= 0)
{
QPoint pt(0, 0);
this->move(pt);
}
else if( y > 0 && y < height)
{
QPoint pt(0, y);
this->move(pt);
}
else if(y >= height)
{
QPoint pt(0, height);
this->move(pt);
}
}
else if( x > 0 && x < width )
{
if(y <= 0)
{
QPoint pt(x, 0);
this->move(pt);
}
else if( y > 0 && y < height)
{
QPoint pt(x, y);
this->move(pt);
}
else if(y >= height)
{
QPoint pt(x, height);
this->move(pt);
}
}
else if( x >= width)
{
if(y <= 0)
{
QPoint pt(width, 0);
this->move(pt);
}
else if( y > 0 && y < height)
{
QPoint pt(width, y);
this->move(pt);
}
else if(y >= height)
{
QPoint pt(width, height);
this->move(pt);
}
}
}
}
#include "MyWidget.h"
#include <QApplication>
#include <QVBoxLayout>
#include <QLabel>
#include "MyDragWidget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
QLabel* label = new QLabel(&w);
label->resize(800, 600);
MyDragWidget mw(pt, label);
mw.setGeometry(30, 30, 80, 100);
mw.setStyleSheet("border:1px solid #FF00FF;border-radius:5px;");
mw.setStyleSheet("background:#642100;");
w.show();
return a.exec();
}
网友评论