Restore the mainwindow size on last open
Hello Everyone,
I just want to restore the size of window of last open window. suppose i have open a window and its size is (500,500) and i have resize it to (600,600).
I have closed the window and again open the project this time window size should be (600,600).
Any help will be appreciable
Re: Restore the mainwindow size on last open
Use QSettings to save / retrieve the size and position of your window. Override the QWidget::showEvent() and QWidget::closeEvent() methods for your window class and save and restore the setting there:
Code:
// Helper class
// QtSettingsHelper.h
#include <QVariant>
class CQtSettingsHelper
{
private:
virtual ~CQtSettingsHelper() = 0;
public:
};
// QtSettingsHelper.cpp
#include "SAQtSettingsHelper.h"
#include <QCoreApplication>
#include <QSettings>
{
settings.beginGroup( group );
QVariant value
= settings.
value( key, defValue
);
settings.endGroup();
return value;
}
{
settings.beginGroup( group );
settings.setValue( key, value );
settings.endGroup();
}
// Example how to use to save / restore window sizes
// Mainindow.h:
class CMainWindow
{
Q_OBJECT
public:
CMainWindow
( QWidget * pParent
= 0 );
~CMainWindow();
protected:
private:
void restoreSettings();
void saveSettings();
};
// MainWindow.cpp
{
saveSettings();
pEvent->accept();
}
void CMainWindow
::showEvent( QShowEvent * pEvent
) {
restoreSettings();
pEvent->accept();
}
static const int sStateVersion = 1000; // Used for versioning state information
void CMainWindow::restoreSettings()
{
QString path
= QStandardPaths
::writableLocation( QStandardPaths
::DocumentsLocation );
resize
( CQtSettingsHelper
::ReadValue( "MainWindow",
"Size",
QSize( 800,
800 ) ).
toSize() );
move
( CQtSettingsHelper
::ReadValue( "MainWindow",
"Position",
QPoint( 50,
50 ) ).
toPoint() );
restoreState( CQtSettingsHelper::ReadValue( "MainWindow", "State" ).toByteArray(), sStateVersion );
}
void CMainWindow::saveSettings()
{
CQtSettingsHelper::WriteValue( "MainWindow", "Size", size() );
CQtSettingsHelper::WriteValue( "MainWindow", "Position", pos() );
CQtSettingsHelper::WriteValue( "MainWindow", "State", saveState( sStateVersion ) );
}
In this code, I am saving not only the size and position of my main window, but also the state, which contains information on the layout of menu, tab, and status bars as well as any dock widgets. Since saveState() and restoreState() and QMainWindow methods, they will not work for other QWidget classes.
The helper class makes it easier to pass arguments to QSettings for save or restore.