Qt6实现支持Win11无边框窗口、自动贴靠布局、缩放(上下左右、四个角拖动缩放)、双击最大化或者恢复最大化之前的位置与大小、窗口阴影实现、去除缩放黑影等基础窗口
注意:
在Qt 6中,默认启用了高DPI缩放(High DPI Scaling),
几乎所有实现都调用到win32函数
需要有一定win32基础
展示
项目架构
主要功能代码
1.引入windows Api
//调用WIN API需要用到的头文件与库
#ifdef Q_OS_WIN
#include <qt_windows.h>
#include <Windowsx.h>
// 编译需要的库
#pragma comment(lib, "user32.lib")
#endif
2.去除窗口边框、设置背景透明(构造函数编写)
//设置窗口标志为无边框
this->setWindowFlags(Qt::FramelessWindowHint);
// 背景透明,防止黑影
setAttribute(Qt::WA_TranslucentBackground);
2.开启贴靠布局(构造函数编写)
#ifdef Q_OS_WIN
HWND hwnd = reinterpret_cast<HWND>(this->winId());
DWORD style = GetWindowLong(hwnd, GWL_STYLE);
SetWindowLongPtr(hwnd, GWL_STYLE, style | WS_OVERLAPPEDWINDOW);
#endif
3.缩放实现
bool Widget::nativeEvent(const QByteArray &eventType, void *message, qintptr *result) {
Q_UNUSED(eventType);
#ifdef Q_OS_WIN
MSG *param = static_cast<MSG *>(message);
switch (param->message) {
case WM_NCCALCSIZE: {
// 使用window默认布局,不加这一段代码,系统无法正确进行最大化
*result = 0;
return true