Home · All Classes · Grouped Classes · Annotated · Functions

Tutorial: Listening for Content Changes

Files:

Applications are able to add documents, remove documents, and modify documents that are in the database. What if an application needs to know when the document database has been modified? For example, an application that display as list of documents would need to know when another application has added or removed a document, so that it can update its display accordingly. (Note, however, that QDocumentSelector could be used in such an application, and QDocumentSelector handles this scenario for us.)

This example is an application that displays the latest image that has been added to the database, if its category matches that of a known document generator. The ChangeListener application incorporates both the code that generates new documents periodically, and the code that listens for changes and updates the image. Normally, the two distinct parts would be in separate classes or even in separate applications. For the sake of convenience, ChangeListener performs both functions.

We first set up a QContentSet with an appropriate QContentFilter, so that we can listen for changes to that set within the database.

    const QString ChangeListenerPrivate::category("ChangeListener"); // or any arbitrary string
    ...
    contentSet = new QContentSet(QContentFilter(QContentFilter::Category,category));
    ...
    connect(contentSet,SIGNAL(changed(const QContentIdList &,QContent::ChangeType)),
            this,SLOT(changed(const QContentIdList &,QContent::ChangeType)));

This will cause the changed(...) slot to be called when any changes have been made concerning ChangeListener documents in the database.

We also set up the QTimer that will cause ChangeListener documents to be created periodically.

    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(generate()));

This QTimer object gets started up by the widget's show event:

    timer->start(MILLISECONDS_DELAY);

where MILLISECONDS_DELAY has been set to 3000. Note that this has been done for the convenience of our contrived example, and a real application would also respond to QWidget's hide event to ensure that no unnecessary processing takes place.

The ChangeListenerPrivate::generate() slot will now be called every three seconds. It programmatically constructs a name for the new picture document, and indexes into an array of image file names. The current image file is then opened and its contents read.

    QFile file(":image/changelistener/" + picNames[picIndex]);
    if ( !file.open(QIODevice::ReadOnly) ) {
        qWarning() << "Cannot open " << picNames[picIndex];
        return;
    }
    QByteArray bytes = file.readAll(); // Not ideal, since you can't check for errors
    file.close();

We then create the new QContent database object, and set its name, type and category.

    QContent newContent;
    // At the least, we want to set the object's name and mime type. We'll also
    // give the object a category, so that all picture objects created by this application
    // can be grouped together.
    newContent.setName(name);
    newContent.setCategories(QStringList(category));
    newContent.setType(QMimeType(picNames[picIndex]).id()); // extract mime type from the file name

Categories are being used in this example because when we exit the application we can remove all the objects that we've created from the database. This will ensure that the user will not be burdened with the inconvenience of having to delete all those documents explicitly.

The QContent database object can now be opened, and the contents of the image file can be written to it.

    QIODevice *ioDevice = newContent.open(QIODevice::WriteOnly);
    if ( !ioDevice ) {
        qWarning("Could not open the new content object to write to!! Document Generator exits.");
        return;
    }
    ioDevice->write(bytes);
    ioDevice->close();
    delete ioDevice;

Lastly, the QContent database object must be persisted to the database by calling the method QContent::commit().

    if ( !newContent.commit() ) {
        qWarning("Could not commit the new content object!! Document generator exits.");
    }

An image document is now being created and saved to the database every three seconds. Meanwhile, the application needs to know about each newly generated document, so that it can be displayed. During object construction, we created a QContentSet and connected its changed(...) signal to our own changed(...) slot. So we can now expect that ChangeListenerPrivate::changed((const QContentIdList &idList,QContent::ChangeType changeType) will also be called approximately every three seconds. We firstly check the change type that has been passed in as a parameter, since we are only interested in documents that have been added. If documents have been added, we iterate through the list of content IDs, even though we only expect to find that one document has been added.

    if ( changeType == QContent::Added ) {
        foreach (QContentId id,idList) {
            QContent content(id);
            ...
        }
    }

If the new document's category matches our own application category, we open the document so that we can read its contents.

            if ( content.isValid() && (content.categories().contains(category)) ) {
                // Open the database object so that you can read its contents.
                QIODevice *ioDevice = content.open(QIODevice::ReadOnly);
                if ( !ioDevice ) {
                    qWarning("Could not open the new content object to read from!!");
                    break;
                }

We create a new QImage object, load it with the document contents, and assign the image to the label used to display pictures.

                // Create the image, and set the label to the new picture.
                QImage image;
                image.load(ioDevice,0);
                imageLabel->setPixmap(QPixmap::fromImage(image));

                // Clean up.
                ioDevice->close();
                // It is the user's reponsibility to delete the return value of QContent::open().
                delete ioDevice;

To install and run the ChangeListener demonstration, carry out the following steps.

  1. Create a new directory (e.g. $HOME/src/changelistener) and copy all the example files to that directory.
        mkdir $HOME/src/changelistener
        cd $HOME/src/changelistener
        cp -r <Qtopia-source-directory>/examples/content/changelistener/* .
        chmod +w *
  2. Build the new application.
        export QPEDIR=<Qtopia-build-directory>
        $QPEDIR/bin/qtopiamake
        make install
  3. Run Qtopia.
        $QPEDIR/bin/runqtopia
  4. Go into the list of Applications and scroll down until you find the ChangeListener application.

When you run the ChangeListener application, you should see a blank screen which updates with a new picture display every three seconds.


Copyright © 2007 Trolltech Trademarks
Qtopia 4.3.0