Simple Persistence “Framework” for Qt4

This “framework” is intended for storing persistent data of small Qt4 Applications easily. It is nice, to have e.g. last used file loaded on a new start or to see the application position/size as used last time.
Unfortunatelly many small application – some prototypes or internal tools – hardly use such basic features. The reason often is the lack of time to implement such “nice-to have” stuff. There are many things to be considered format, place of data, unified load/store procedures, etc.
This framework helps to use persistency with very minimal implementation overhead. These are the steps for using it:

  1. include “persistence.h”
  2. call once macro PERSISTENCE_INIT after QApplication has been created ( usually called in main )
  3. For each item to store call once macro PERSISTENT ( usually called in constructor body of the class containing this variable or property )

That’s it. The data will be stored on exit and loaded on start.

The macro PERSISTENCE_INIT has two parameters – company name and app name e.g.: PERSISTENCE_INIT( “My Company”, “My App Name” )
The macro PERSISTENT has three parameters. There are three variants
at the moment, e.g:
PERSISTENT(“MyIntVar”, &SomeIntMember, this )
PERSISTENT(“MyStrVar”, &SomeQStringMember, this )
PERSISTENT(“MyProperty”, this, “geometry”)
The two first variants store a value of a int/QString member
The third variant stores the value of a QObject property (e.g. geometry)

Example:

#include <QtGui> 
#include "persistence.h" //(1.) include persistence "framework"
#include "slotvarmapper.h"

/// Variables to be persistent
int myIntValue=4711;
QString myStrValue="Hello";

int main(int argc, char *argv[])
{

    QApplication a(argc, argv);
    //(2.)Init persistence
    PERSISTENCE_INIT( "MyCompany", "MyTestApp" );

    //create a simple GUI containing 2 line-edits
    QWidget w;
    w.setLayout(new QVBoxLayout);
    QLineEdit *intLine = new QLineEdit (&w);
    QLineEdit *strLine = new QLineEdit (&w);
    w.layout()->addWidget(intLine);
    w.layout()->addWidget(strLine);

    //Helper instance for storing line-edit value in myIntValue
    StrSlotToIntVarMapper im( myIntValue,&w );
    QObject::connect(intLine,SIGNAL(textChanged(QString)),&im,SLOT(processSlot(QString)));

    //Helper instance for storing line-edit value in myStrValue
    StrSlotToStrVarMapper sm( myStrValue,&w );
    QObject::connect(strLine,SIGNAL(textChanged(QString)),&sm,SLOT(processSlot(QString)));

    //(3.)Declare variables and property to be pesistent. Thats ALL!
    PERSISTENT("LastIntValue", &myIntValue, 0)
    PERSISTENT("LastStrValue", &myStrValue, 0)
    PERSISTENT("LastGeometry", &w, "geometry")

    //Set initial values, or values from persistence
    intLine->setText(QString::number(myIntValue));
    strLine->setText(myStrValue);

    w.show();
    return a.exec();
    //(4.)Persistent values are stored on exit automatically
}

About admin

Comments are closed.