还原窗口的几何图形

本文档介绍如何使用几何属性保存和还原窗口的几何图形。在 Windows 上,这基本上是在调用show() 之前,将QWindow::geometry() 和调用QWindow::setGeometry() 的结果存储在下一个会话中。

在 X11 上,这可能不起作用,因为不可见窗口还没有框架。窗口管理器稍后会装饰窗口。在这种情况下,窗口会根据装饰框的大小向屏幕底部/右角移动。虽然 X 提供了避免这种偏移的方法,但有些窗口管理器未能实现这一功能。

当使用 Qt Widgets时,Qt 提供了保存和恢复窗口几何图形和状态的函数。QWidget::saveGeometry()保存窗口的几何图形和最大化/全屏状态,而QWidget::restoreGeometry()则还原几何图形和全屏状态。还原函数还会检查还原的几何图形是否超出了可用屏幕几何图形的范围,如果超出,则会对其进行适当修改:

void MyMainWindow::closeEvent(QCloseEvent *event)
{
    QSettings settings("MyCompany", "MyApp");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
    QMainWindow::closeEvent(event);
}
void MainWindow::readSettings()
{
    QSettings settings("MyCompany", "MyApp");
    restoreGeometry(settings.value("myWidget/geometry").toByteArray());
    restoreState(settings.value("myWidget/windowState").toByteArray());
}

另一种解决方案是同时存储pos() 和size() ,并在调用show() 之前使用QWidget::resize() 和move() 还原几何图形。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.