Wednesday, May 16, 2007

Restoring a Window's Geometry

Since version 4.2, Qt provides functions that saves and restores a window's geometry and state for you. QWidget::saveGeometry() saves the window geometry and maximized/fullscreen state, while QWidget::restoreGeometry() restores it. The restore function also checks if the restored geometry is outside the available screen geometry, and modifies it as appropriate if it is.

The rest of this document describes how to save and restore the geometry using the geometry properties. On Windows, this is basically storing the result of QWidget::geometry() and calling QWidget::setGeometry() in the next session before calling show(). On X11, this won't work because an invisible window doesn't have a frame yet. The window manager will decorate the window later. When this happens, the window shifts towards the bottom/right corner of the screen depending on the size of the decoration frame. Although X provides a way to avoid this shift, most window managers fail to implement this feature.

A workaround is to call setGeometry() after show(). This has the two disadvantages that the widget appears at a wrong place for a millisecond (results in flashing) and that currently only every second window manager gets it right. A safer solution is to store both pos() and size() and to restore the geometry using QWidget::resize() and move() before calling show(), as demonstrated in the following code snippets (from the Application example):

 void MainWindow::readSettings()
{
QSettings settings("Trolltech", "Application Example");
QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
QSize size = settings.value("size", QSize(400, 400)).toSize();
resize(size);
move(pos);
}

void MainWindow::writeSettings()
{
QSettings settings("Trolltech", "Application Example");
settings.setValue("pos", pos());
settings.setValue("size", size());
}

This method works on Windows, Mac OS X, and most X11 window managers.

No comments: