|  | Home · All Classes · Main Classes · Annotated · Grouped Classes · Functions |

# In Sync with Outlook

This example demonstrates the use of ActiveQt to automate Outlook. The example makes use of the dumpcpp tool to generate a C++ namespace for the type library describing the Outlook Object Model.

        TEMPLATE = app
        TARGET   = qutlook
        CONFIG  += qaxcontainer

        !exists("c:\program files\Microsoft Office\Office10\msoutl.olb") {
            message("Microsoft Outlook type library not found at standard location!")
            REQUIRES += Outlook

The project file checks if the the Outlook type library is located in the standard location. If not, then the generated makefile will just print an error message.

        } else {
            TYPELIBS = "c:\program files\Microsoft Office\Office10\msoutl.olb"

            HEADERS  = addressview.h
            SOURCES  = addressview.cpp main.cpp
        }

If the type library could be located, then it is added to the `TYPELIBS` variable, and the use of the dumpcpp tool is turned on. The build step will now run the dumpcpp tool whenever the type library changes, and will generate a header and a cpp file (in this case, `msoutl.h` and `msoutl.cpp`) that declare and implement an easy to use Qt-like API to the Outlook objects.

        class AddressView : public QWidget
        {
            Q_OBJECT

        public:
            AddressView(QWidget *parent = 0);

        protected slots:
            void addEntry();
            void changeEntry();
            void itemSelected(const QModelIndex &index);

            void updateOutlook();

        protected:
            AddressBookModel *model;

            QTreeView *treeView;
            QPushButton *add, *change;
            QLineEdit *iFirstName, *iLastName, *iAddress, *iEMail;
        };

The AddressView class declares a QWidget subclass for the user interface. The QTreeView widget will display the contents of Outlook's Contact folder.

        #include "addressview.h"

        #include <qhash.h>
        #include <qfile.h>
        #include <qlabel.h>
        #include <qlayout.h>
        #include <qlineedit.h>
        #include <qpushbutton.h>
        #include <qtreeview.h>

        #include "msoutl.h"

        uint qHash(const QModelIndex &key)
        {
            return (key.row()+1) * (key.column()+1) + key.column();
        }

The implementation includes the required header files (including the `msoutl.h` header generated by the dumpcpp tool), and provides a `qHash` implementation for QModelIndex, which allows caching of data in the application (thus reducing the number of calls to Outlook).

        class AddressBookModel : public QAbstractListModel
        {
        public:
            AddressBookModel(AddressView *parent);
            ~AddressBookModel();

            int rowCount(const QModelIndex &parent = QModelIndex()) const;
            int columnCount(const QModelIndex &parent) const;
            QVariant headerData(int section, Qt::Orientation orientation, int role) const;
            QVariant data(const QModelIndex &index, int role) const;

            void changeItem(const QModelIndex &index, const QString &firstName, const QString &lastName, const QString &address, const QString &email);
            void addItem(const QString &firstName, const QString &lastName, const QString &address, const QString &email);
            void update();

        private:
            Outlook::Application outlook;
            Outlook::Items * contactItems;

            mutable QHash<QModelIndex, QStringList> cache;
        };

The AddressBookModel class implements a QAbstractListModel that communicates directly with Outlook, using a QHash for caching.

        AddressBookModel::AddressBookModel(AddressView *parent)
        : QAbstractListModel(parent)
        {
            if (!outlook.isNull()) {
                Outlook::NameSpace session(outlook.Session());
                session.Logon();
                Outlook::MAPIFolder *folder = session.GetDefaultFolder(Outlook::olFolderContacts);
                contactItems = new Outlook::Items(folder->Items());
                connect(contactItems, SIGNAL(ItemAdd(IDispatch*)), parent, SLOT(updateOutlook()));
                connect(contactItems, SIGNAL(ItemChange(IDispatch*)), parent, SLOT(updateOutlook()));
                connect(contactItems, SIGNAL(ItemRemove()), parent, SLOT(updateOutlook()));

                delete folder;
            }
        }

The constructor initializes Outlook. For Outlook APIs that return subobjects of type `IDispatch` the return value has to be put into an object of the correct type. The various signals Outlook provides to notify about contents changes are connected to the `updateOutlook()` slot.

        AddressBookModel::~AddressBookModel()
        {
            delete contactItems;

            if (!outlook.isNull())
                Outlook::NameSpace(outlook.Session()).Logoff();
        }

The destructor logs off from the session.

        int AddressBookModel::rowCount(const QModelIndex &) const
        {
            return contactItems ? contactItems->Count() : 0;
        }

        int AddressBookModel::columnCount(const QModelIndex &parent) const
        {
            return 4;
        }

        QVariant AddressBookModel::headerData(int section, Qt::Orientation orientation, int role) const
        {
            if (role != DisplayRole)
                return QVariant();

            switch (section) {
            case 0:
                return "First Name";
            case 1:
                return "Last Name";
            case 2:
                return "Address";
            case 3:
                return "Email";
            default:
                break;
            }

            return QVariant();
        }

The `rowCount()` implementation returns the number of entries as reported by Outlook. `columnCount` and `headerData` are implemented to show four columns in the tree view.

        QVariant AddressBookModel::data(const QModelIndex &index, int role) const
        {
            if (!index.isValid() || role != DisplayRole)
                return QVariant();

            QStringList data;
            if (cache.contains(index)) {
                data = cache.value(index);
            } else {
                Outlook::ContactItem contact(contactItems->Item(index.row() + 1));
                data << contact.FirstName() << contact.LastName() << contact.HomeAddress() << contact.Email1Address();
                cache.insert(index, data);
            }

            if (index.column() < data.count())
                return data.at(index.column());

            return QVariant();
        }

The `data()` implementation is the core of the model. If the requested data is in the cache the cached value is used, otherwise the data is acquired from Outlook.

        void AddressBookModel::changeItem(const QModelIndex &index, const QString &firstName, const QString &lastName, const QString &address, const QString &email)
        {
            Outlook::ContactItem item(contactItems->Item(index.row() + 1));

            item.SetFirstName(firstName);
            item.SetLastName(lastName);
            item.SetHomeAddress(address);
            item.SetEmail1Address(email);

            item.Save();

            cache.take(index);
        }

The `changeItem()` slot is called when the user changes the current entry using the user interface. The Outlook item is accessed using the Outlook API, and is modified using the property setters. Finally, the item is saved to Outlook, and removed from the cache. Note that the model does not signal the view of the data change, as Outlook will emit a signal on it's own.

        void AddressBookModel::addItem(const QString &firstName, const QString &lastName, const QString &address, const QString &email)
        {
            Outlook::ContactItem item(outlook.CreateItem(Outlook::olContactItem));
            if (!item.isNull()) {
                item.SetFirstName(firstName);
                item.SetLastName(lastName);
                item.SetHomeAddress(address);
                item.SetEmail1Address(email);

                item.Save();
            }
        }

The `addItem()` slot calls the CreateItem method of the Outlook to create a new contact item, sets the properties of the new item to the values entered by the user and saves the item.

        void AddressBookModel::update()
        {
            cache.clear();

            emit reset();
        }

The `update()` slot clears the cache, and emits the reset() signal to notify the view about the data change requiring a redraw of the contents.

        AddressView::AddressView(QWidget *parent)
        : QWidget(parent)
        {
            QGridLayout *mainGrid = new QGridLayout(this);

            QLabel *liFirstName = new QLabel("First &Name", this);
            liFirstName->resize(liFirstName->sizeHint());
            mainGrid->addWidget(liFirstName, 0, 0);

            QLabel *liLastName = new QLabel("&Last Name", this);
            liLastName->resize(liLastName->sizeHint());
            mainGrid->addWidget(liLastName, 0, 1);

            QLabel *liAddress = new QLabel("Add&ress", this);
            liAddress->resize(liAddress->sizeHint());
            mainGrid->addWidget(liAddress, 0, 2);

            QLabel *liEMail = new QLabel("&E-Mail", this);
            liEMail->resize(liEMail->sizeHint());
            mainGrid->addWidget(liEMail, 0, 3);

            add = new QPushButton("A&dd", this);
            add->resize(add->sizeHint());
            mainGrid->addWidget(add, 0, 4);
            connect(add, SIGNAL(clicked()), this, SLOT(addEntry()));

            iFirstName = new QLineEdit(this);
            iFirstName->resize(iFirstName->sizeHint());
            mainGrid->addWidget(iFirstName, 1, 0);
            liFirstName->setBuddy(iFirstName);

            iLastName = new QLineEdit(this);
            iLastName->resize(iLastName->sizeHint());
            mainGrid->addWidget(iLastName, 1, 1);
            liLastName->setBuddy(iLastName);

            iAddress = new QLineEdit(this);
            iAddress->resize(iAddress->sizeHint());
            mainGrid->addWidget(iAddress, 1, 2);
            liAddress->setBuddy(iAddress);

            iEMail = new QLineEdit(this);
            iEMail->resize(iEMail->sizeHint());
            mainGrid->addWidget(iEMail, 1, 3);
            liEMail->setBuddy(iEMail);

            change = new QPushButton("&Change", this);
            change->resize(change->sizeHint());
            mainGrid->addWidget(change, 1, 4);
            connect(change, SIGNAL(clicked()), this, SLOT(changeEntry()));

            treeView = new QTreeView(this);
            treeView->setSelectionMode(QTreeView::SingleSelection);
            treeView->setRootIsDecorated(false);

            model = new AddressBookModel(this);
            treeView->setModel(model);

            connect(treeView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(itemSelected(QModelIndex)));

            mainGrid->addWidget(treeView, 2, 0, 1, 5);
        }

        void AddressView::updateOutlook()
        {
            model->update();
        }

        void AddressView::addEntry()
        {
            if (!iFirstName->text().isEmpty() || !iLastName->text().isEmpty() ||
                 !iAddress->text().isEmpty() || !iEMail->text().isEmpty()) {
                model->addItem(iFirstName->text(), iFirstName->text(), iAddress->text(), iEMail->text());
            }

            iFirstName->setText("");
            iLastName->setText("");
            iAddress->setText("");
            iEMail->setText("");
        }

        void AddressView::changeEntry()
        {
            QModelIndex current = treeView->currentIndex();

            if (current.isValid())
                model->changeItem(current, iFirstName->text(), iLastName->text(), iAddress->text(), iEMail->text());
        }

        void AddressView::itemSelected(const QModelIndex &index)
        {
            if (!index.isValid())
                return;

            QAbstractItemModel *model = treeView->model();
            iFirstName->setText(model->data(model->index(index.row(), 0)).toString());
            iLastName->setText(model->data(model->index(index.row(), 1)).toString());
            iAddress->setText(model->data(model->index(index.row(), 2)).toString());
            iEMail->setText(model->data(model->index(index.row(), 3)).toString());
        }

The rest of the file implements the user interface.

        #include <qapplication.h>

        #include "addressview.h"

        int main(int argc, char ** argv)
        {
            QApplication a(argc, argv);

            AddressView view;
            view.setWindowTitle("Qt Example - Looking at Outlook");
            view.show();

            return a.exec();
        }

The `main()` entry point function finally instantiates the user interface and enters the event loop.

To build the example you must first build the QAxContainer library. Then run your make tool in `examples/qutlook` and run the resulting `qutlok.exe`.