恢复窗口的几何属性
本文档介绍了如何使用几何属性来保存和恢复窗口的几何属性。在 Windows 系统上,这基本上是先将 `QWindow::geometry()` 的结果存储起来,然后在下次会话中调用 `QWindow::setGeometry()`,最后再调用 `show()`。
在 X11 环境下,此方法可能无法正常工作,因为不可见的窗口尚无边框。窗口管理器会在稍后为窗口添加装饰边框。此时,窗口会根据装饰边框的大小向屏幕底部或右下角偏移。尽管 X 提供了一种避免这种偏移的方法,但某些窗口管理器未能实现此功能。
在使用 Qt Widgets时,Qt Widgets 提供了用于保存和恢复小部件窗口几何尺寸及状态的函数。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() 恢复几何位置。
© 2026 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.