Ejemplo de Qutlook (ActiveQt)
El ejemplo de Qutlook muestra cómo utilizar ActiveQt para automatizar Outlook. El ejemplo utiliza la herramienta dumpcpp para generar un espacio de nombres en C++ para la biblioteca de tipos que describe el modelo de objetos de Outlook.
El archivo de proyecto del ejemplo tiene este aspecto:
TEMPLATE = app
TARGET = qutlook
QT += widgets axcontainer
TYPELIBS = $$system(dumpcpp -getfile {00062FFF-0000-0000-C000-000000000046})
isEmpty(TYPELIBS) {
message("Microsoft Outlook type library not found!")
REQUIRES += Outlook
} else {
HEADERS = addressview.h
SOURCES = addressview.cpp main.cpp
}El archivo de proyecto utiliza la herramienta dumpcpp para añadir una biblioteca de tipos de MS Outlook al proyecto. Si esto falla, el archivo «makefile» generado simplemente mostrará un mensaje de error; de lo contrario, el paso de compilación ejecutará la herramienta «dumpcpp» sobre la biblioteca de tipos y generará un archivo de cabecera y un archivo «cpp» (en este caso, msoutl.h y msoutl.cpp) que declaran e implementan una API fácil de usar para los objetos de Outlook.
class AddressView : public QWidget
{
Q_OBJECT
public:
explicit AddressView(QWidget *parent = nullptr);
protected slots:
void addEntry();
void changeEntry();
void itemSelected(const QModelIndex &index);
void updateOutlook();
protected:
AddressBookModel *model;
QTreeView *m_treeView;
QPushButton *m_addButton;
QPushButton *m_changeButton;
QLineEdit *m_firstName;
QLineEdit *m_lastName;
QLineEdit *m_address;
QLineEdit *m_email;
};La clase `AddressView` es una subclase de ` QWidget ` destinada a la interfaz de usuario. El widget ` QTreeView ` mostrará el contenido de la carpeta «Contactos» de Outlook tal y como lo proporciona ` model`.
#include "addressview.h"
#include "msoutl.h"
#include <QtWidgets>
class AddressBookModel : public QAbstractListModel
{
public:
explicit AddressBookModel(AddressView *parent);
virtual ~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 *folderItems = nullptr;
mutable QHash<QModelIndex, QStringList> cache;
};La clase `AddressBookModel` es una subclase de ` QAbstractListModel ` que se comunica directamente con Outlook, utilizando un ` QHash ` para el almacenamiento en caché.
AddressBookModel::AddressBookModel(AddressView *parent)
: QAbstractListModel(parent)
{
if (!outlook.isNull()) {
Outlook::NameSpace session(outlook.Session());
session.Logon();
Outlook::MAPIFolder *folder = session.GetDefaultFolder(Outlook::olFolderContacts);
folderItems = new Outlook::Items(folder->Items());
connect(folderItems, SIGNAL(ItemAdd(IDispatch*)), parent, SLOT(updateOutlook()));
connect(folderItems, SIGNAL(ItemChange(IDispatch*)), parent, SLOT(updateOutlook()));
connect(folderItems, SIGNAL(ItemRemove()), parent, SLOT(updateOutlook()));
delete folder;
}
}El constructor inicializa Outlook. Las distintas señales que proporciona Outlook para notificar los cambios en el contenido se conectan a la ranura updateOutlook().
AddressBookModel::~AddressBookModel()
{
delete folderItems;
if (!outlook.isNull())
Outlook::NameSpace(outlook.Session()).Logoff();
}El destructor cierra la sesión.
int AddressBookModel::rowCount(const QModelIndex &) const
{
return folderItems ? folderItems->Count() : 0;
}
int AddressBookModel::columnCount(const QModelIndex & /*parent*/) const
{
return 4;
}La implementación de ` rowCount() ` devuelve el número de entradas según lo informado por Outlook. ` columnCount ` y ` headerData ` se han implementado para mostrar cuatro columnas en la vista de árbol.
QVariant AddressBookModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
switch (section) {
case 0:
return tr("First Name");
case 1:
return tr("Last Name");
case 2:
return tr("Address");
case 3:
return tr("Email");
default:
break;
}
return QVariant();
}La implementación de ` headerData() ` devuelve cadenas codificadas de forma fija.
QVariant AddressBookModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || role != Qt::DisplayRole)
return QVariant();
QStringList data;
if (cache.contains(index)) {
data = cache.value(index);
} else {
Outlook::ContactItem contact(folderItems->Item(index.row() + 1));
if (contact.Class() == Outlook::OlObjectClass::olContact)
data << contact.FirstName() << contact.LastName() << contact.HomeAddress() << contact.Email1Address();
cache.insert(index, data);
}
if (index.column() < data.size())
return data.at(index.column());
return QVariant();
}La implementación de ` data() ` constituye el núcleo del modelo. Si los datos solicitados se encuentran en la caché, se utiliza el valor almacenado; de lo contrario, los datos se obtienen de Outlook.
void AddressBookModel::changeItem(const QModelIndex &index, const QString &firstName, const QString &lastName, const QString &address, const QString &email)
{
Outlook::ContactItem item(folderItems->Item(index.row() + 1));
if (item.Class() != Outlook::OlObjectClass::olContact)
return; // Not a contact
item.SetFirstName(firstName);
item.SetLastName(lastName);
item.SetHomeAddress(address);
item.SetEmail1Address(email);
item.Save();
cache.take(index);
}La ranura changeItem() se invoca cuando el usuario modifica la entrada actual mediante la interfaz de usuario. Se accede al elemento de Outlook mediante la API de Outlook y se modifica utilizando los setters de propiedades. Por último, el elemento se guarda en Outlook y se elimina de la caché. Ten en cuenta que el modelo no notifica a la vista el cambio de datos, ya que Outlook emitirá una señal por sí mismo.
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();
}
}La ranura « addItem() » llama al método «CreateItem» de Outlook para crear un nuevo elemento de contacto, establece las propiedades del nuevo elemento con los valores introducidos por el usuario y guarda el elemento.
void AddressBookModel::update()
{
beginResetModel();
cache.clear();
endResetModel();
}La ranura « update() » borra la caché y emite la señal «reset()» para notificar a la vista que el cambio en los datos requiere un redibujado del contenido.
AddressView::AddressView(QWidget *parent)
: QWidget(parent)
{
QGridLayout *mainGrid = new QGridLayout(this);
QLabel *firstNameLabel = new QLabel(tr("First &Name"), this);
firstNameLabel->resize(firstNameLabel->sizeHint());
mainGrid->addWidget(firstNameLabel, 0, 0);
QLabel *lastNameLabel = new QLabel(tr("&Last Name"), this);
lastNameLabel->resize(lastNameLabel->sizeHint());
mainGrid->addWidget(lastNameLabel, 0, 1);
QLabel *addressLabel = new QLabel(tr("Add&ress"), this);
addressLabel->resize(addressLabel->sizeHint());
mainGrid->addWidget(addressLabel, 0, 2);
QLabel *emailLabel = new QLabel(tr("&E-Mail"), this);
emailLabel->resize(emailLabel->sizeHint());
mainGrid->addWidget(emailLabel, 0, 3);
m_addButton = new QPushButton(tr("A&dd"), this);
m_addButton->resize(m_addButton->sizeHint());
mainGrid->addWidget(m_addButton, 0, 4);
connect(m_addButton, &QPushButton::clicked, this, &AddressView::addEntry);
m_firstName = new QLineEdit(this);
m_firstName->resize(m_firstName->sizeHint());
mainGrid->addWidget(m_firstName, 1, 0);
firstNameLabel->setBuddy(m_firstName);
m_lastName = new QLineEdit(this);
m_lastName->resize(m_lastName->sizeHint());
mainGrid->addWidget(m_lastName, 1, 1);
lastNameLabel->setBuddy(m_lastName);
m_address = new QLineEdit(this);
m_address->resize(m_address->sizeHint());
mainGrid->addWidget(m_address, 1, 2);
addressLabel->setBuddy(m_address);
m_email = new QLineEdit(this);
m_email->resize(m_email->sizeHint());
mainGrid->addWidget(m_email, 1, 3);
emailLabel->setBuddy(m_email);
m_changeButton = new QPushButton(tr("&Change"), this);
m_changeButton->resize(m_changeButton->sizeHint());
mainGrid->addWidget(m_changeButton, 1, 4);
connect(m_changeButton, &QPushButton::clicked, this, &AddressView::changeEntry);
m_treeView = new QTreeView(this);
m_treeView->setSelectionMode(QTreeView::SingleSelection);
m_treeView->setRootIsDecorated(false);
model = new AddressBookModel(this);
m_treeView->setModel(model);
connect(m_treeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &AddressView::itemSelected);
mainGrid->addWidget(m_treeView, 2, 0, 1, 5);
}
void AddressView::updateOutlook()
{
model->update();
}
void AddressView::addEntry()
{
if (!m_firstName->text().isEmpty() || !m_lastName->text().isEmpty() ||
!m_address->text().isEmpty() || !m_email->text().isEmpty()) {
model->addItem(m_firstName->text(), m_lastName->text(), m_address->text(), m_email->text());
}
m_firstName->clear();
m_lastName->clear();
m_address->clear();
m_email->clear();
}
void AddressView::changeEntry()
{
QModelIndex current = m_treeView->currentIndex();
if (current.isValid())
model->changeItem(current, m_firstName->text(), m_lastName->text(), m_address->text(), m_email->text());
}
void AddressView::itemSelected(const QModelIndex &index)
{
if (!index.isValid())
return;
QAbstractItemModel *model = m_treeView->model();
m_firstName->setText(model->data(model->index(index.row(), 0)).toString());
m_lastName->setText(model->data(model->index(index.row(), 1)).toString());
m_address->setText(model->data(model->index(index.row(), 2)).toString());
m_email->setText(model->data(model->index(index.row(), 3)).toString());
}El resto del archivo implementa la interfaz de usuario utilizando únicamente las API de Qt, es decir, sin comunicarse directamente con Outlook.
#include "addressview.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
AddressView view;
view.setWindowTitle(QObject::tr("Qt Example - Looking at Outlook"));
view.show();
return a.exec();
}La función de punto de entrada ` main() ` crea finalmente una instancia de la interfaz de usuario y entra en el bucle de eventos.
Para compilar el ejemplo, primero debes compilar la biblioteca QAxContainer. A continuación, ejecuta tu herramienta «make» en examples/activeqt/qutlook y ejecuta el archivo resultante qutlook.exe.
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.