qt 窗口无标题在桌面移动,不可移出可视范围之外

下面是基类的源代码,把所需求移动的窗口类继承这个基类即可

头文件:

/************************************************************************/
/*BaseWidget.h                                                          */
/************************************************************************/

#ifndef BASEWIDGET_H
#define BASEWIDGET_H

#include <QWidget>

class BaseWidget : public QWidget
{
	Q_OBJECT

public:
	BaseWidget(QWidget *parent = 0);
	~BaseWidget();
protected:
	void mousePressEvent(QMouseEvent *event);
	void mouseMoveEvent(QMouseEvent *event);
	void mouseReleaseEvent(QMouseEvent*event);

	bool m_moving;//用来标记是否鼠标移动
	QPoint m_offset;
private:
};

#endif // BASEWIDGET_H

CPP文件:

/************************************************************************/
/* BaseWidget.cpp                                                       */
/************************************************************************/

#include "BaseWidget.h"
#include <QMouseEvent>
#include <QDesktopWidget>
#include <QApplication>

BaseWidget::BaseWidget(QWidget *parent)
	: QWidget(parent,Qt::FramelessWindowHint),m_moving(false)
{

}

BaseWidget::~BaseWidget()
{
	
}

void BaseWidget::mousePressEvent( QMouseEvent *event )
{
	if((event->button() == Qt::LeftButton))
	{
		m_moving = true;
		m_offset = event->pos();
	}
}

void BaseWidget::mouseMoveEvent( QMouseEvent *event )
{
	if(m_moving)
	{
		//方法1:
		QDesktopWidget* desktop = QApplication::desktop();
		QRect windowRect(desktop->availableGeometry());
		QRect widgetRect(this->geometry());
		QPoint point(event->globalPos() - m_offset);

		//以下是防止窗口拖出可见范围外
		//左边
		if (point.x() <= 0)
		{
			point = QPoint(0,point.y());
		}
		//右边
		int y = windowRect.bottomRight().y() - this->size().height();
		if (point.y() >= y && widgetRect.topLeft().y() >= y)
		{
			point = QPoint(point.x(),y);
		}
		//上边
		if (point.y() <= 0)
		{
			point = QPoint(point.x(),0);
		}
		//下边
		int x = windowRect.bottomRight().x() - this->size().width();
		if (point.x() >= x && widgetRect.topLeft().x() >= x)
		{
			point = QPoint(x,point.y());
		}
		move(point);
		//方法2:
		//可以通过判断QRect windowRect是否包含(contains) QRect widgetRect 再移动
		//这里没有给出代码
	}
	//如果只是要求移动窗口,用以下代码即可实现
	//move(event->globalPos() - m_offset);
}

void BaseWidget::mouseReleaseEvent( QMouseEvent*event )
{
	if(event->button() == Qt::LeftButton)
		m_moving = false;
}



  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值