上一篇已经介绍了如何使用无边框进行大小调整:https://labisart.com/blog/index.php/Home/Index/article/aid/252
不过这个解决方案有个小问题就是边框会抖动。
现在介绍下其他2个方法:
1、方法1,使用 Windows 原生的消息,实现 WM_NCHITTEST 消息,典型方案在这里,没测试过:
https://stackoverflow.com/questions/43505580/qt-windows-resizable-frameless-window
bool MainWindow::nativeEvent(const QByteArray& eventType, void* message, long* result)
{
MSG* msg = static_cast<MSG*>(message); if (msg->message == WM_NCHITTEST)
{
if (isMaximized())
{ return false;
}
*result = 0; const LONG borderWidth = 8;
RECT winrect; GetWindowRect(reinterpret_cast<HWND>(winId()), &winrect); // must be short to correctly work with multiple monitors (negative coordinates)
short x = msg->lParam & 0x0000FFFF; short y = (msg->lParam & 0xFFFF0000) >> 16; bool resizeWidth = minimumWidth() != maximumWidth(); bool resizeHeight = minimumHeight() != maximumHeight(); if (resizeWidth)
{ //left border
if (x >= winrect.left && x < winrect.left + borderWidth)
{
*result = HTLEFT;
} //right border
if (x < winrect.right && x >= winrect.right - borderWidth)
{
*result = HTRIGHT;
}
} if (resizeHeight)
{ //bottom border
if (y < winrect.bottom && y >= winrect.bottom - borderWidth)
{
*result = HTBOTTOM;
} //top border
if (y >= winrect.top && y < winrect.top + borderWidth)
{
*result = HTTOP;
}
} if (resizeWidth && resizeHeight)
{ //bottom left corner
if (x >= winrect.left && x < winrect.left + borderWidth &&
y < winrect.bottom && y >= winrect.bottom - borderWidth)
{
*result = HTBOTTOMLEFT;
} //bottom right corner
if (x < winrect.right && x >= winrect.right - borderWidth &&
y < winrect.bottom && y >= winrect.bottom - borderWidth)
{
*result = HTBOTTOMRIGHT;
} //top left corner
if (x >= winrect.left && x < winrect.left + borderWidth &&
y >= winrect.top && y < winrect.top + borderWidth)
{
*result = HTTOPLEFT;
} //top right corner
if (x < winrect.right && x >= winrect.right - borderWidth &&
y >= winrect.top && y < winrect.top + borderWidth)
{
*result = HTTOPRIGHT;
}
} if (*result != 0) return true;
QWidget *action = QApplication::widgetAt(QCursor::pos()); if (action == this){
*result = HTCAPTION; return true;
}
} return false;
}理论上是没问题的,不过呢跨平台就比较蛋疼,我一般不用这种原生的解决方案,除非没办法了。
2、方法2,在Mainwindow上层显示一个widget,不过这个widget要透明显示,然后在paintEvent()中用QPainter画矩形边框,跟随鼠标走动,看起来就像是Mainwindow拉伸一样:

这样代码就可以跨平台使用了。