使用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 "ui_frameless_widget.h"
#include <windows.h>
#include <windowsx.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;
}

本文介绍了如何在Qt中创建一个无边框窗口,并通过重写`nativeEvent`方法实现拖动和拉伸窗口的功能。通过设置`setWindowFlags(Qt::FramelessWindowHint)`消除窗口边框,然后在`nativeEvent`中处理`WM_NCHITTEST`消息,根据鼠标位置判断拖动和拉伸的区域,从而实现自定义的窗口操作行为。
523

被折叠的 条评论
为什么被折叠?



