CardView Example

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

#include "window.h"

inline 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("CardView Example"))
{
    Grid::loadTranslation();

    m_grid = new Qtitan::CardGrid(this);

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

    QSqlDatabase db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), QStringLiteral("database_demo"));
    db.setDatabaseName(path + QStringLiteral("/database_yachts.sqlite"));
    db.setHostName(QString());
    db.setPort(-1);
    if (!db.open(QString(), QString()))
    {
        QSqlError err = db.lastError();
        QSqlDatabase::removeDatabase(tr("database_demo"));
        QMessageBox::critical(0, tr("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("data"), m_grid);
    if (model == Q_NULL)
    {
        QMessageBox::critical(0, tr("SQL Error"), tr("Error: SQL data base is not valid."));
        QApplication::exit(1);
        return;
    }

    // Configure grid view
    m_grid->setViewType(Qtitan::CardGrid::CardView);
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();

    view->beginUpdate();

    //view->options().setScrollRowStyle(ScrollByPixel);
    view->options().setRowAutoHeight(true);
    view->options().setCellWidth(250);
    view->options().setSupportedDropActions(Qt::CopyAction);
    view->options().setModelItemsDragEnabled(true);

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

    view->setModel(model);

    Qtitan::GridCardColumn* column = (Qtitan::GridCardColumn *)view->getColumnByModelColumnName(tr("Photo"));
    column->setRowSpan(5);
    column->setEditorType(GridEditor::Picture);
    column->setDecorationColor(Qt::yellow);

    column = (Qtitan::GridCardColumn *)view->getColumnByModelColumnName(tr("Description"));
    column->setEditorType(GridEditor::Memo);
    //Add cell button to the column.
    column->addButton(GridColumn::ChoiceButtonIcon, Qtitan::AtEnd);
    connect(column, SIGNAL(buttonClicked(CellButtonClickEventArgs*)), this, SLOT(cellButtonClicked(CellButtonClickEventArgs*)));

    column = (Qtitan::GridCardColumn *)view->getColumnByModelColumnName(tr("Built Year"));
    column->setEditorType(GridEditor::Date);
    static_cast<GridDateEditorRepository *>(column->editorRepository())->setDisplayFormat(tr("yyyy"));

    column = (Qtitan::GridCardColumn *)view->getColumnByModelColumnName(tr("id"));
    view->removeColumn(column->index());

    setDemoWidget(m_grid, createSettingsWidget());
    view->endUpdate();

    //view->bestFit();
    column = (Qtitan::GridCardColumn *)view->getColumnByModelColumnName(tr("Registry"));
    column->setGroupIndex(0);
    view->expandAll();
}

QWidget* Window::createSettingsWidget()
{
    //Create settings widget
    QWidget* settings = new QWidget(this);
    QVBoxLayout* l = new QVBoxLayout(settings);

    l->addLayout(createStyleSetting());

    QCheckBox* fastScrollCheck = new QCheckBox(settings);
    fastScrollCheck->setText(tr("Fast scroll effect"));
    connect(fastScrollCheck, SIGNAL(stateChanged(int)), this, SLOT(fastScrollChanged(int)));
    l->addWidget(fastScrollCheck);
    fastScrollCheck->setChecked(true);

    QCheckBox* dottedLineCheck = new QCheckBox(settings);
    dottedLineCheck->setText(tr("Dotted grid line"));
    connect(dottedLineCheck, SIGNAL(stateChanged(int)), this, SLOT(dottedLineChanged(int)));
    l->addWidget(dottedLineCheck);
    dottedLineCheck->setChecked(true);

    QLabel* label = new QLabel(this);
    QHBoxLayout* hl = new QHBoxLayout(0);
    label->setText(tr("Grid line style:"));
    QComboBox* lineStylesSelect = new QComboBox(settings);

    lineStylesSelect->addItem(QStringLiteral("None"));
    lineStylesSelect->addItem(QStringLiteral("Both"));
    lineStylesSelect->addItem(QStringLiteral("Both2D"));
    lineStylesSelect->addItem(QStringLiteral("Horizontal"));
    lineStylesSelect->addItem(QStringLiteral("Horizontal2D"));
    lineStylesSelect->addItem(QStringLiteral("Vertical"));
    lineStylesSelect->addItem(QStringLiteral("Vertical2D"));
    connect(lineStylesSelect, SIGNAL(currentIndexChanged(int)), this, SLOT(selectGridLineStyles(int)));
    hl->addWidget(label);
    hl->addWidget(lineStylesSelect);
    l->addLayout(hl);
    lineStylesSelect->setCurrentIndex(2);

    QLabel* alignLabel = new QLabel(this);
    QHBoxLayout* alignLayout = new QHBoxLayout(0);
    alignLabel->setText(tr("Items alignement:"));
    QComboBox* alignSelect = new QComboBox(settings);

    alignSelect->addItem(tr("Left"));
    alignSelect->addItem(tr("Center"));
    alignSelect->addItem(tr("Right"));
    connect(alignSelect, SIGNAL(currentIndexChanged(int)), this, SLOT(alignSelectChanged(int)));
    alignLayout->addWidget(alignLabel);
    alignLayout->addWidget(alignSelect);
    l->addLayout(alignLayout);
    alignSelect->setCurrentIndex(0);

    QHBoxLayout* l2 = new QHBoxLayout(0);
    QPushButton* button1 = new QPushButton(settings);
    button1->setText(tr("Save to XML/FastInfoset"));
    connect(button1, SIGNAL(clicked()), this, SLOT(saveLayout()));
    l2->addWidget(button1);
    QPushButton* button2 = new QPushButton(settings);
    button2->setText(tr("Load from XML/FastInfoset"));
    connect(button2, SIGNAL(clicked()), this, SLOT(loadLayout()));
    l2->addWidget(button2);
    l->addLayout(l2);

    QCheckBox* zoomEnable = new QCheckBox(settings);
    zoomEnable->setText(tr("Zoom enabled"));
    zoomEnable->setChecked(true);
    connect(zoomEnable, SIGNAL(stateChanged(int)), this, SLOT(zoomEnabledChanged(int)));
    l->addWidget(zoomEnable);

    QCheckBox* zoomIndicator = new QCheckBox(settings);
    zoomIndicator->setText(tr("Show zoom indicator"));
    zoomIndicator->setChecked(true);
    connect(zoomIndicator, SIGNAL(stateChanged(int)), this, SLOT(zoomIndicatorChanged(int)));
    l->addWidget(zoomIndicator);

    QSlider* zoomSlider = new QSlider(settings);
    zoomSlider->setOrientation(Qt::Horizontal);
    zoomSlider->setTickPosition(QSlider::TicksBothSides);
    zoomSlider->setMinimum(25);
    zoomSlider->setMaximum(300);
    zoomSlider->setTickInterval(25);
    zoomSlider->setSingleStep(25);
    zoomSlider->setValue(100);
    connect(zoomSlider, SIGNAL(sliderMoved(int)), this, SLOT(zoomValueChanged(int)));
    connect(m_grid->view<Qtitan::GridCardView>(), SIGNAL(zoomChanged(int)), zoomSlider, SLOT(setValue(int)));
    l->addWidget(zoomSlider);

    QCheckBox* cellAutoRaise = new QCheckBox(settings);
    cellAutoRaise->setText(tr("Auto raise cell button"));
    connect(cellAutoRaise, SIGNAL(stateChanged(int)), this, SLOT(cellButtonAutoRaiseEnabled(int)));
    cellAutoRaise->setChecked(true);
    l->addWidget(cellAutoRaise);

    QCheckBox* transparentBox = new QCheckBox(settings);
    transparentBox->setText(tr("Transparent Background"));
    connect(transparentBox, SIGNAL(stateChanged(int)), this, SLOT(transparentBackgroundEnabled(int)));
    transparentBox->setChecked(false);
    l->addWidget(transparentBox);

    QPushButton* printButton = new QPushButton(settings);
    printButton->setText(tr("Print Preview"));
    connect(printButton, SIGNAL(clicked()), this, SLOT(printPreview()));
    l->addWidget(printButton);

    return settings;
}

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

void Window::fastScrollChanged(int state)
{
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();
    view->options().setFastScrollEffect(state == Qt::Checked);
}

void Window::dottedLineChanged(int state)
{
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();
    QPen pen = view->options().gridLinePen();
    pen.setStyle(state == Qt::Checked ? Qt::DotLine : Qt::SolidLine);
    view->options().setGridLinePen(pen);
}

void Window::selectGridLineStyles(int index)
{
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();
    switch (index)
    {
    case 0:
        view->options().setGridLines(Qtitan::LinesNone);
        break;
    case 1:
        view->options().setGridLines(Qtitan::LinesBoth);
        break;
    case 2:
        view->options().setGridLines(Qtitan::LinesBoth2D);
        break;
    case 3:
        view->options().setGridLines(Qtitan::LinesHorizontal);
        break;
    case 4:
        view->options().setGridLines(Qtitan::LinesHorizontal2D);
        break;
    case 5:
        view->options().setGridLines(Qtitan::LinesVertical);
        break;
    case 6:
        view->options().setGridLines(Qtitan::LinesVertical2D);
        break;
    default:
        view->options().setGridLines(Qtitan::LinesBoth);
    }
}

void Window::alignSelectChanged(int index)
{
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();
    switch (index)
    {
    case 0:
        view->cardOptions().setItemAlignment(Qt::AlignLeft);
        break;
    case 1:
        view->cardOptions().setItemAlignment(Qt::AlignCenter);
        break;
    case 2:
        view->cardOptions().setItemAlignment(Qt::AlignRight);
        break;
    default:
        view->cardOptions().setItemAlignment(Qt::Alignment());
    }
}

void Window::saveLayout()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save QtitanDataGrid Layout to File"),
        QStringLiteral("qtitan-layout"), QStringLiteral("XML (*.xml);;FastInfoset (*.fi)"));
    if (fileName.isEmpty())
        return;
    if (QFileInfo(fileName).completeSuffix().contains(QStringLiteral("xml"), Qt::CaseInsensitive))
        m_grid->saveLayoutToFile(fileName);
    else
    {
        FastInfosetStreamWriter writer(fileName);
        m_grid->saveLayoutToXML(&writer);
    }
}

void Window::loadLayout()
{
    QStringList files = QFileDialog::getOpenFileNames(this, tr("Open QtitanDataGrid Layout File"),
        QString(), QStringLiteral("XML (*.xml);;FastInfoset (*.fi)"));
    QString fileName = files.size() > 0 ? files[0] : QString();
    if (fileName.isEmpty())
        return;
    if (QFileInfo(fileName).completeSuffix().contains(QStringLiteral("xml"), Qt::CaseInsensitive))
        m_grid->loadLayoutFromFile(fileName);
    else
    {
        FastInfosetStreamReader reader(fileName);
        m_grid->loadLayoutFromXML(&reader);
    }
}

void Window::zoomEnabledChanged(int state)
{
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();
    view->options().setZoomEnabled(state == Qt::Checked);
}

void Window::zoomIndicatorChanged(int state)
{
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();
    view->options().setZoomIndicatorActive(state == Qt::Checked);
}

void Window::zoomValueChanged(int value)
{
    double factor = qCeil((double)value / 25) * 25;
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();
    view->options().setZoomFactor(factor / 100);
}

void Window::cellButtonAutoRaiseEnabled(int state)
{
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();
    view->options().setCellButtonAutoRaise(state == Qt::Checked);
}

void Window::transparentBackgroundEnabled(int state)
{
    Qtitan::GridCardView* view = m_grid->view<Qtitan::GridCardView>();
    view->options().setTransparentBackground(state == Qt::Checked);

    view->options().setAlternatingRowColors(!view->options().alternatingRowColors());
}

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::cellButtonClicked(CellButtonClickEventArgs* args)
{
    QMessageBox::information(this, tr("Cell button clicked"),
        tr("Clicked: Button - %1, Column Title - %2, RowIndex - %3").arg(args->buttonIndex()).arg(args->column()->caption()).arg(args->row().rowIndex()));
}

void Window::cellButtonStateChanged(CellButtonEventArgs* args)
{
    if (args->row().rowIndex() == 1 || args->row().rowIndex() == 2)
        args->setEnabled(false);
}

void Window::printPreview()
{
    m_grid->view<Qtitan::GridCardView>()->printPreview();
}