RelationMode Example

#include <QtGui>
#include <QtSql>
#include <QMessageBox>

#include "window.h"

static QSqlTableModel* createSQLModel(QSqlDatabase& dataBase, const QString& tableName, QObject* parent)
{
    if (tableName.isEmpty() || !dataBase.isValid())
        return Q_NULL;
    if (!dataBase.isOpen() && !dataBase.open())
        return Q_NULL;

    QSqlTableModel* sqlModel = new QSqlTableModel(parent, dataBase);
    sqlModel->setTable(tableName);
    sqlModel->select();
    if (sqlModel->lastError().type() != QSqlError::NoError)
        Q_DELETE_AND_NULL(sqlModel);
    return sqlModel;
}

Window::Window()
: DemoMainWindow(QStringLiteral("QtitanDataGrid"), QStringLiteral(QTN_VERSION_DATAGRID_STR), tr("Relation and MasterDetails modes Example"))
{
    Grid::loadTranslation();

    m_tabs = new QTabWidget(this);
    createRelationGrid();
    createMasterDetailsGrid();

    setDemoWidget(m_tabs, 0);
}

void Window::createRelationGrid()
{
    m_relationGrid = new Qtitan::Grid(this);

    QSqlTableModel* model = new QSqlTableModel(m_relationGrid);
    model->setTable(tr("employee"));
    model->select();
    model->setEditStrategy(QSqlTableModel::OnFieldChange);

    // Configure grid view
    m_relationGrid->setViewType(Qtitan::Grid::TableView);
    Qtitan::GridTableView* view = m_relationGrid->view<Qtitan::GridTableView>();
    view->setModel(model);

    view->options().setNewRowPlace(Qtitan::AtEnd);
    view->options().setSupportedDropActions(Qt::CopyAction);

    Qtitan::GridTableColumn* column = (Qtitan::GridTableColumn *)view->getColumnByCaption(tr("id"));
    column->editorRepository()->setEditable(true);

    //Connect Grid's context menu handler.
    connect(view, SIGNAL(contextMenu(ContextMenuEventArgs*)), this, SLOT(contextMenu(ContextMenuEventArgs* )));

    QSqlTableModel* city = new QSqlTableModel(m_relationGrid);
    city->setTable(tr("city"));
    city->select();

    QSqlTableModel* country = new QSqlTableModel(m_relationGrid);
    country->setTable(tr("country"));
    country->select();

    column = (Qtitan::GridTableColumn *)view->getColumnByCaption(tr("city"));
    //column->setEditorType(GridEditor::ComboBox);
    column->setEditorType(GridEditor::Table);
    column->dataBinding()->setRelationMode(GridModelDataBinding::Relation);
    column->dataBinding()->setRelationModel(city);
    column->dataBinding()->setForeignKey(tr("id"));
    column->dataBinding()->setRoleMapping(Qt::DisplayRole, tr("name"));

    column = (Qtitan::GridTableColumn *)view->getColumnByCaption(tr("country"));
    column->setEditorType(GridEditor::ComboBox);
    column->dataBinding()->setRelationMode(GridModelDataBinding::Relation);
    column->dataBinding()->setRelationModel(country);
    column->dataBinding()->setForeignKey(tr("id"));
    column->dataBinding()->setRoleMapping(Qt::DisplayRole, tr("name"));

    m_tabs->insertTab(0, m_relationGrid, tr("Relation Mode"));
}

void Window::createMasterDetailsGrid()
{
    m_masterDetailsGrid = new Qtitan::Grid(this);

#ifndef Q_OS_ANDROID
    QString path = QApplication::applicationDirPath();
    path += QStringLiteral("/../examples/SQLFiles/assets");
#else
    QString path = QDir::homePath();
    copyAssetFile(path, "films.sqlite");
#endif

    QSqlDatabase db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), QStringLiteral("database_demo"));
    db.setDatabaseName(path + QStringLiteral("/films.sqlite"));
    db.setHostName(QString());
    db.setPort(-1);
    if (!db.open(QString(), QString()))
    {
        QSqlError err = db.lastError();
        QSqlDatabase::removeDatabase(QStringLiteral("database_demo"));
        QMessageBox::critical(0, QStringLiteral("SQL Error"), tr("Error: Can't open database - %1, error - %2").arg(db.databaseName()).arg(err.text()));
        QApplication::exit(1);
        return;
    }

    QSqlTableModel* model = createSQLModel(db, QStringLiteral("Films"), m_masterDetailsGrid);
    if (model == Q_NULL)
    {
        QMessageBox::critical(0, tr("SQL Error"), tr("Error: SQL data base is not valid."));
        QApplication::exit(1);
        return;
    }

    QSqlTableModel* countriesModel = new CountriesDemoModel(m_masterDetailsGrid, db);
    countriesModel->setTable(tr("Countries"));
    countriesModel->select();
    if (countriesModel->lastError().type() != QSqlError::NoError)
    {
        QMessageBox::critical(0, tr("Demo Error"), tr("Error: SQL data base is not valid."));
        QApplication::exit(1);
        return;
    }

    // Configure grid view
    m_masterDetailsGrid->setViewType(Qtitan::Grid::TableView);
    Qtitan::GridTableView* view = m_masterDetailsGrid->view<Qtitan::GridTableView>();

    view->beginUpdate();

    view->options().setBorderWidth(0);
    view->options().setRowAutoHeight(true);
    view->options().setScrollRowStyle(Qtitan::ScrollByPixel);
    view->options().setSupportedDropActions(Qt::CopyAction);

    connect(view, SIGNAL(editorEditModeChanged(GridEditor *)), this, SLOT(editorModeChanged(GridEditor *)));

    view->setModel(model);

    Qtitan::GridTableColumn* column = (Qtitan::GridTableColumn *)view->getColumnByModelColumnName(tr("Goofs"));
    column->setEditorType(GridEditor::Memo);

    column = (Qtitan::GridTableColumn *)view->getColumnByModelColumnName(tr("Plot"));
    column->setEditorType(GridEditor::Memo);

    column = (Qtitan::GridTableColumn *)view->getColumnByModelColumnName(tr("Photo"));
    column->setEditorType(GridEditor::Picture);

    column = (Qtitan::GridTableColumn *)view->getColumnByModelColumnName(tr("Country"));
    column->editorRepository()->setEditorActivationPolicy(GridEditor::ActivateByAnyEvents);
    column->dataBinding()->setRelationMode(GridModelDataBinding::Relation);
    column->dataBinding()->setRelationModel(countriesModel);
    column->dataBinding()->setForeignKey(tr("id"));
    column->dataBinding()->setRoleMapping(Qt::DisplayRole, tr("Name"));
    column->dataBinding()->setRoleMapping(Qt::DecorationRole, tr("Flag"));
    column->setEditorType(GridEditor::ComboBox);

    QSqlTableModel* actorsModel = new QSqlTableModel(0, db);
    actorsModel->setTable(tr("Actors"));
    actorsModel->select();
    column = (Qtitan::GridTableColumn *)view->getColumnByModelColumnName(tr("Cast"));
    column->dataBinding()->setRelationMode(GridModelDataBinding::MasterDetailsRelation);
    column->dataBinding()->setRelationModel(actorsModel);
    column->dataBinding()->setForeignKey(tr("film_id"));
    column->dataBinding()->setRoleMapping(Qt::DisplayRole, tr("Name"));
    column->setEditorType(GridEditor::Table);

    view->endUpdate();

    view->bestFit();

    m_tabs->insertTab(1, m_masterDetailsGrid, tr("MasterDetails Mode"));
}

void Window::setShadeColor(const QColor& color)
{
    m_relationGrid->themeManager()->setShadeColor(color);
    m_masterDetailsGrid->themeManager()->setShadeColor(color);
}

void Window::editorModeChanged(GridEditor* editor)
{
    if (editor->site()->dataBinding()->columnName() != tr("Cast"))
        return;
    //Customize grid editor here
    Qtitan::TableComboBox* box = qobject_cast<Qtitan::TableComboBox *>(editor->getCellWidget());
    if (box == 0)
        return;
    Qtitan::Grid* grid = box->grid();
    Qtitan::GridTableView* view = grid->view<Qtitan::GridTableView>();
    view->options().setRowAutoHeight(true);
    view->options().setNewRowText(tr("Click here to add new actor"));
    //view->options().setFocusFollowsMouse(true);

    Qtitan::GridTableColumn* column = (Qtitan::GridTableColumn *)view->getColumnByModelColumnName(tr("Actor photo"));
    if (column)
        column->setEditorType(GridEditor::Picture);
}

void Window::contextMenu(ContextMenuEventArgs* args)
{
    args->contextMenu()->addAction(tr("Print Preview"), this, SLOT(printPreview()));
    args->contextMenu()->addSeparator();
    args->contextMenu()->addAction(tr("Developer Machines on the Web"), this, SLOT(showCompanyWebSite()));
}

void Window::printPreview()
{
    m_masterDetailsGrid->view<Qtitan::GridTableView>()->printPreview();
}

/* CountriesDemoModel */
CountriesDemoModel::CountriesDemoModel(QObject *parent, QSqlDatabase db)
: QSqlTableModel(parent, db)
{
}

QVariant CountriesDemoModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DecorationRole)
    {
        QModelIndex pixmapindex = QSqlTableModel::index(index.row(), 1, index.parent());
        QPixmap pixmap;
        qtn_qvariant_to_pixmap(QSqlTableModel::data(pixmapindex, Qt::DisplayRole), pixmap);
        return pixmap;
    }
    return QSqlTableModel::data(index, role);
}