Qt实现可拉伸和可移动无边框的Widget

使用FramelessWindowHint设置之后Widget不能移动和拉伸,需要自己实现

复制
setWindowFlags(Qt::FramelessWindowHint);

.h文件

#pragma once
#include <QWidget>
class FramelessWidget : public QWidget {
Q_OBJECT
public:
FramelessWidget(QWidget* Parent = Q_NULLPTR);
void set_boundary(int32_t Boundary, int32_t MoveHeight);
protected:
bool nativeEvent(const QByteArray& EventType, void* pMessage,
long* pResult) override;
private:
int32_t m_Boundary; //调整拉伸生效的范围
int32_t m_MoveHeight; //调整拖动生效的范围
};

.cpp文件

默认4边4角都可拉伸,整个窗体不可移动,要减少拉伸边数直接注释即可

#include <windows.h>
#include <windowsx.h>
#include "ui_frameless_widget.h"
FramelessWidget::FramelessWidget(QWidget* parent)
: QWidget(parent),
m_Boundary(0),
m_MoveHeight(0) //默认无法拖动和拉伸
{
// setAttribute(Qt::WA_TranslucentBackground, true);
setWindowFlags(Qt::Window | Qt::FramelessWindowHint); //设置为无边框窗口
}
void FramelessWidget::set_boundary(int32_t Boundary, int32_t MoveHeight) {
m_Boundary = Boundary;
m_MoveHeight = MoveHeight;
}
bool FramelessWidget::nativeEvent(const QByteArray& EventType, void* pMessage,
long* pResult) {
MSG* pMsg = (MSG*)pMessage;
switch (pMsg->message) {
case WM_NCHITTEST:
int PosX = GET_X_LPARAM(pMsg->lParam) - this->frameGeometry().x();
int PosY = GET_Y_LPARAM(pMsg->lParam) - this->frameGeometry().y();
if (childAt(PosX, PosY) == 0) {
//拖拽生效区域
if (PosY <= m_MoveHeight) {
*pResult = HTCAPTION;
}
} else {
return false;
}
if (PosX < m_Boundary && PosY > (height() - m_Boundary) &&
PosY < height())
*pResult = HTBOTTOMLEFT; //左下
else if (PosX > (width() - m_Boundary) && PosX < width() &&
PosY > (height() - m_Boundary) && PosY < height())
*pResult = HTBOTTOMRIGHT; //右下
else if (PosX < m_Boundary && PosY < m_Boundary)
*pResult = HTTOPLEFT; //左上
else if (PosX > (width() - m_Boundary) && PosX < width() &&
PosY < m_Boundary)
*pResult = HTTOPRIGHT; //右上
else if (PosX < m_Boundary)
*pResult = HTLEFT; //左
else if (PosX > (width() - m_Boundary) && PosX < width())
*pResult = HTRIGHT; //右
else if (PosY < m_Boundary)
*pResult = HTTOP; //上
else if (PosY > (height() - m_Boundary) && PosY < height())
*pResult = HTBOTTOM; //下
return true;
}
return false;
}

参考链接

posted @   umichan  阅读(1182)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示