Article Save and Restore your View State

From mitk.org
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.


The BlueBerry workbench provides a simple API to save and restore the state of a View. Using this facility makes your View more user-friendly and better integrated in the application.


Introduction

Every view in the workbench has to inherit from berry::IViewPart which declares the following two methods for hooking into a Views lifecycle:

  • void Init(IViewSite::Pointer site, IMemento::Pointer memento)
  • void SaveState(IMemento::Pointer memento)

Those two methods should be overwritten in your View implementation.

Saving State

Use the provided IMemento instance in the SaveState method to save arbitrary information. For example, if you want to save the checked state of a Qt ComboBox named combo, write code like:

<syntaxhighlight lang="cpp"> void SaveState(IMemento::Pointer memento) {

 IMemento::Pointer guiState = memento->CreateChild("guistate");
 guiState->PutBoolean("combo", combo->isChecked());

} </syntaxhighlight>

For maintenance reasons, you should not use inlined string constants but rather use static const members (for example).


Restoring State

If you overwrite the IViewPart::Init(...) method, you get access to a IMemento instance which contains the previously saved contents. Be sure to check for a null memento though, if no state has been saved before.

Note that the Init(...) method is called before the CreatePartControl method (or its Qt variant CreateQtPartControl), therefore we need to temporarily save the memento so it can be used after the GUI elements have been initialized. To restore the state of the previously used Qt ComboBox, your code would look like:

<syntaxhighlight lang="cpp"> void Init(IViewSite::Pointer site, IMemento::Pointer memento) {

 Superclass::Init(site, memento);
 
 // save the memento in a member variable
 m_StateMemento = memento;

}

void CreateQtPartControl(QWidget* parent) {

 // initialize GUI elements
 ...
 bool comboChecked = false;
 if (m_StateMemento)
 {
   IMemento::Pointer guiState = m_StateMemento->GetChild("guistate");
   guiState->GetBoolean("combo", comboChecked);
   // release the memento smartpointer
   m_StateMemento = 0;
 }
 combo->setChecked(comboChecked);

} </syntaxhighlight>


Preferences or Memento

Preferences should be used whenever a user changeable value which does not have a direct representation in your view should be persisted. The Init/SaveState methods of IViewPart allow you to save and restore your user interface inside one "application session". If a view is explicitly closed by a user, the GUI state will be reverted to its default state when the same view is opened again (a null IMemento will be supplied to Init()).