13e. wxWidgets – Persistent Objects

OVERVIEW

Persistent objects are widgets in wxWidgets which have the ability to save and restore their visual state between different program invocations. For instance, if a window is moved or sized during a program run, then using persistence we can restore the window to the same state during subsequent runs.

Only a few wxWidgets classes have this ability so far : top level windows like wxFrame, wxDialog and objects which are based on wxBookCtrlBase like wxNoteBook, wxListBook etc.

Apart from the existing classes which support persistence, you can add persistence to your own custom wxWidget classes too.

In the sample code below, we create a simple wxFrame and restore it back if it was saved. The three screenshots are for the first initial load, then moving and resizing it, exiting and running it a second time.

SAMPLE CODE

persistent.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
	#include <wx/wx.h>
#endif

class Persistent:public wxFrame {

	public:
		Persistent(const wxString &title);
};
persistent.cpp
#include "persistent.h"


Persistent::Persistent(const wxString& title):
	wxFrame(NULL, -1, title, wxDefaultPosition, wxSize(500,200)) {
        Center();

}
main.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
	#include <wx/wx.h>
#endif

class Main: public wxApp {

	public:
		virtual bool OnInit();
};
main.cpp
#include "main.h"
#include "persistent.h"
#include <wx/persist.h>
#include <wx/persist/toplevel.h>

IMPLEMENT_APP(Main)

bool Main::OnInit() {
	Persistent *app = new Persistent(wxT("Persistent Objects"));
	app->SetName(wxT("testobject"));
	if (!wxPersistenceManager::Get().RegisterAndRestore((wxFrame*) app))
		app->Show(true);
	else
		app->Show(true);
}

The output is shown below

Be the first to comment

Leave a Reply

Your email address will not be published.


*