1 开发测试环境
IDE:VS2017
Qt:5.14.2 x64
操作系统:Win10、Win11
实现效果:
2 实现
网上搜索Qt窗口的无边框化实现方案有很多,但从实现的难易程度,以及效果上来说,最优
的还是通过Windows消息来实现,即重新实现Qt窗口的nativeEvent方法。该方案不仅实现了无边
框窗口,还保留了窗口的拖动、贴边等系统特性,以下为实现代码(以QWidget为例,
QMainWindow、QDialog可以平移过去):
#include "ui/frameless_widget.h"
#include <windows.h>
#include <windowsx.h>
#pragma comment (lib,"user32.lib")
FramelessWidget::FramelessWidget(QWidget *parent) : QWidget(parent)
, movale_(true)
, resizable_(true)
, border_width_(5)
, title_bar_(Q_NULLPTR)
, just_maximized_(false)
{
this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint);
this->installEventFilter(this);
HWND hwnd = (HWND)this->winId();
DWORD style = ::GetWindowLong(hwnd, GWL_STYLE);
::SetWindowLong(hwnd, GWL_STYLE, style | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_CAPTION);
}
FramelessWidget::~FramelessWidget()
{
}
void FramelessWidget::setTitleBar(QWidget *title_bar)
{
title_bar_ = title_bar;
title_bar_->installEventFilter(this);
}
void FramelessWidget::showEvent(QShowEvent *event)
{
this->setAttribute(Qt::WA_Mapped);
QWidget::showEvent(event);
}
bool FramelessWidget::eventFilter(QObject *watched, QEvent *event)
{
if (watched == this)
{
if (event->type() == QEvent::WindowStateChange)
{
if (this->windowState() == Qt::WindowNoState)
{
movale_ = true;
resizable_ = true;
}
else
{
mo