這實際上就是我最終做的。 底部的「framegeometry」部分是必要的,以彌補它看起來的widget的邊界。
QT += gui-private
需要在代碼中的.pro文件以下工作
#include <WinUser.h>
#include <qpa/qplatformnativeinterface.h>
static QWindow* windowForWidget(const QWidget* widget)
{
QWindow* window = widget->windowHandle();
if (window)
return window;
const QWidget* nativeParent = widget->nativeParentWidget();
if (nativeParent)
return nativeParent->windowHandle();
return 0;
}
#include <QWindow>
static HWND getHWNDForWidget(const QWidget* widget)
{
QWindow* window = ::windowForWidget(widget);
if (window && window->handle())
{
QPlatformNativeInterface* natInterface = QGuiApplication::platformNativeInterface();
return static_cast<HWND>(natInterface->nativeResourceForWindow(QByteArrayLiteral("handle"), window));
}
return 0;
}
void SaveSize(QWidget* w)
{
QSize size;
QPoint pos;
RECT pRect = { 0 };
HWND hwnd = getHWNDForWidget(w);
GetWindowRect(hwnd, &pRect);
auto left = w->frameGeometry().left();
auto right = w->frameGeometry().right();
auto width = w->width();
pos.setX(pRect.left);
pos.setY(pRect.top);
size.setWidth(pRect.right - pRect.left - (right - left - width));
size.setHeight(pRect.bottom - pRect.top);
//.... the rest of the code
}