ICS

QicsTable Documentation Set

spreadsheet.cpp

/****************************************************************************
** $RCSfile: spread_cpp.html,v $ $Date: 2008/06/23 16:31:53 $
**
** Copyright ( C ) 2002-2003 Integrated Computer Solutions, Inc.
** All rights reserved.
**
** This file is part of an example program for QicsTable.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

//----------------------------------------------------------------------------
//   Object that wraps a QicsTable and does an "Excel-lent" spreadsheet.
//   Note that QSA support can be added in by modfiying the .pro file
//----------------------------------------------------------------------------

#include <QApplication>
#include <QStringList>
#include <QMenu>
#include <QTextStream>
#include <QList>
#include <QPixmap>
#include <QLabel>
#ifdef CREATE_OBJS_WITH_QICSTABLE
#include <QPrintDialog>
#include <QPrinter>
#endif

#include <QicsComboCellDisplay.h>
#include "spreadsheet.h"
#include "QicsDataItemCurrencyFormatter.h"

// taken from $QTDIR/examples/textedit

#include "editcopy.xpm"
#include "editcut.xpm"
#include "editpaste.xpm"
#include "filenew.xpm"
#include "fileopen.xpm"
#include "filesave.xpm"
//#include "fillcolor.xpm"
#include "fontcolor.xpm"
#include "sortasc.xpm"
#include "sortdesc.xpm"
#include "textbold.xpm"
#include "textitalic.xpm"
#include "textunder.xpm"
#include "textleft.xpm"
#include "textcenter.xpm"
#include "textright.xpm"

/*---------------------------------------------------------------------------
 *  Function:  Spreadsheet constructor
 *
 *  Description:
 *    Constructor the Spreadsheet object.  Creates a QMainWindow with a menu
 *    and toolbar, a QicsTable, and connects the appropriate slots to load
 *    and manipulate data.
 */

Spreadsheet::Spreadsheet(QWidget* p) :
    QMainWindow(p)
{

    setWindowTitle("Excellent Spreadsheet Demo");

    /*
     *  Pulldown Menu
     */

    // File
    QMenu* file = new QMenu("&File",this);
    menuBar()->addMenu(file);

    file->addAction("&New", this, SLOT(fileNew()), QKeySequence("Ctrl+N"));
    file->addAction("&Open", this, SLOT(openFile()), QKeySequence("Ctrl+O"));
    file->addAction("&Save", this, SLOT(saveFile()), QKeySequence("Ctrl+S"));
    file->addAction("S&ave As ...", this, SLOT(saveFileAs()));
    file->addSeparator();
#ifdef CREATE_OBJS_WITH_QICSTABLE
    file->addAction("P&rint", this, SLOT(print()), QKeySequence("Ctrl+P"));
    file->addSeparator();
#endif
    file->addAction("E&xit", qApp, SLOT(closeAllWindows()), QKeySequence("Ctrl+x"));

    // Edit
    QMenu* edit = new QMenu("&Edit",this);
    menuBar()->addMenu(edit);

    edit->addAction("&Copy", this, SLOT(copy()),QKeySequence("Ctrl+C"));
    edit->addAction("&Paste", this, SLOT(paste()),QKeySequence("Ctrl+V"));

    // View
    QMenu* view = new QMenu("&View",this);
    menuBar()->addMenu(view);

    // Insert
    QMenu* insert = new QMenu("&Insert",this);
    menuBar()->addMenu(insert);

    insert->addAction("&Row", this, SLOT(insertRow()));
    insert->addAction("&Column", this, SLOT(insertColumn()));

    // Format
    QMenu* format = new QMenu("F&ormat",this);
    menuBar()->addMenu(format);

    QMenu* rowFormat =  new QMenu("&Row",this);

    format->addMenu(rowFormat);

    format->addSeparator();

    format->addAction("&Font...", this, SLOT(formatFont()));
    format->addAction("Fore&ground...", this,
                       SLOT(formatForegroundColor()));
    format->addAction("&Background...", this,
                       SLOT(formatBackgroundColor()));

    // Tools
    QMenu* tools = new QMenu("&Tools",this);
    menuBar()->addMenu(tools);
    tools->addAction("&Script Editor", this, SLOT(showQSAWorkbench()));
    tools->addAction("Script &Test", this, SLOT(testScripts()));
    tools->addAction("Save Scripts", this, SLOT(saveScripts()));

    // Data
    QMenu* data = new QMenu("&Data",this);
    menuBar()->addMenu(data);
    data->addAction("Sort &Ascending", this, SLOT(sortAscending()));
    data->addAction("Sort &Descending", this, SLOT(sortDescending()));

    // Spans
    QMenu* spans = new QMenu("&Spans",this);
    menuBar()->addMenu(spans);
    spans->addAction("Add Span", this, SLOT(addSpan()));
    spans->addAction("Remove Span", this, SLOT(removeSpan()));
    /*
     * Toolbars
     */

    // File operation toolbar

    QToolBar* fileTools = new QToolBar("File tools",this);
    fileTools->addAction(QIcon(filenew),"&New", this, SLOT(fileNew()));

    fileTools->addAction(QIcon(fileopen),"&Open", this, SLOT(openFile()));

    fileTools->addAction(QIcon(filesave),"&Save", this, SLOT(saveFile()));

    fileTools->addSeparator();

    // Edit operations

    fileTools->addAction(QIcon(editcut),"&Cut", this, SLOT(cut()));

    fileTools->addAction(QIcon(editcopy),"&Copy", this, SLOT(copy()));

    fileTools->addAction(QIcon(editpaste),"Paste", this, SLOT(paste()));

    fileTools->addSeparator();

    // Sort

    fileTools->addAction(QIcon(sortasc_xpm),"Sort Ascending", this, SLOT(sortAscending()));

    fileTools->addAction(QIcon(sortdesc_xpm),"Sort Descending", this, SLOT(sortDescending()));

    fileTools->addSeparator();

    addToolBar(fileTools);
    // Font name and point size

    QToolBar* fontTools = new QToolBar("Font tools",this);

    fontFamilyCombo = new QComboBox(fontTools);
    fontSizeCombo = new QComboBox(fontTools);

    fontTools->addWidget(fontFamilyCombo);
    fontTools->addWidget(fontSizeCombo);


    connect(fontFamilyCombo, SIGNAL(activated(int)),
        this, SLOT(selectFont(int)));

    connect(fontSizeCombo, SIGNAL(activated(int)),
        this, SLOT(selectFont(int)));

    QFontDatabase fdb;
    QStringList families = fdb.families();
    fontFamilyCombo->addItems(families);

    // Font format operations

    boldAction = new QAction(QIcon(textbold),"Bold", this);
    fontTools->addAction(boldAction);
    boldAction->setCheckable(true);
    connect(boldAction,SIGNAL(triggered()),this,SLOT(textBold()));

    italicAction = new QAction(QIcon(textitalic),"Italic", this);
    fontTools->addAction(italicAction);
    italicAction->setCheckable(true);
    connect(italicAction,SIGNAL(triggered()),this,SLOT(textItalic()));

    underlineAction = new QAction(QIcon(textunder),"Underline", this);
    fontTools->addAction(underlineAction);
    underlineAction->setCheckable(true);
    connect(underlineAction,SIGNAL(triggered()),this,SLOT(textUnderline()));

    fontTools->addSeparator();

    // Text Alignment

    textLeftAction = new QAction(QIcon(textleft),"Align Left", this);
    fontTools->addAction(textLeftAction);
    textLeftAction->setCheckable(true);
    connect(textLeftAction,SIGNAL(triggered()),this,SLOT(textAlignLeft()));

    textCenterAction = new QAction(QIcon(textcenter),"Align Center", this);
    fontTools->addAction(textCenterAction);
    textCenterAction->setCheckable(true);
    connect(textCenterAction,SIGNAL(triggered()),this,SLOT(textAlignCenter()));

    textRightAction = new QAction(QIcon(textright),"Align Right", this);
    fontTools->addAction(textRightAction);
    textRightAction->setCheckable(true);
    connect(textRightAction,SIGNAL(triggered()),this,SLOT(textAlignRight()));

    fontTools->addSeparator();

    // Formatters
    QToolButton* currencyTB =
        new QToolButton(fontTools);
    currencyTB->setText("$");
    connect(currencyTB, SIGNAL(clicked()),
            this, SLOT(setCurrencyFormatter()));

    fontTools->addWidget(currencyTB);

    fontTools->addSeparator();

    // Colors


    fontTools->addAction(
    QPixmap(fontcolor_xpm), "Font Color",
                    this, SLOT(formatForegroundColor()));

    addToolBar(fontTools);

    /*
     *  Table
     */

    QWidget *vbox = new QWidget(this);
    QVBoxLayout *vboxLayout = new QVBoxLayout();
    QWidget *cellrow = new QWidget(vbox);
    QHBoxLayout *cellrowLayout = new QHBoxLayout();
    cellrowLayout->setMargin(2);
    cellrowLayout->addWidget(new QLabel("Cell Value = "));

    cellLineEdit = new QLineEdit();
    cellrowLayout->addWidget(cellLineEdit);
    cellrow->setLayout(cellrowLayout);

    connect(cellLineEdit, SIGNAL(returnPressed()),
            this, SLOT(cellLineUpdate()));

    int lastRow = 10;
    int lastCol = 50;

    // create the data model
    dm = new QicsDataModelDefault(lastRow, lastCol);

    // create the table, using the data model we created above
    table = new QicsTable(dm);
    vboxLayout->addWidget(cellrow);
    vboxLayout->addWidget(table);
    vbox->setLayout(vboxLayout);

    connect(table, SIGNAL(selectionListChanged(bool)),
            this, SLOT(updateSelection(bool)));

    // Set some visual resources on the table
    table->rowHeader()->setAlignment(Qt::AlignHCenter);
    table->columnHeader()->setAlignment(Qt::AlignHCenter);
    table->rowHeader()->column(0)->setWidthInChars(3);
    table->mainGridRef().setBackgroundColor(Qt::white);

    // Set row sorting mode to non-distractive sord
    table->setRowsSortingMode( Qics::QicsStableSort );

    table->show();

    setFontCombos(table->font());

    setCentralWidget(vbox);

    statusBar()->showMessage("Ready", -1);

    fileName = QString::null;
#ifdef QSA

    // QSA Initialization
    project = new QSProject( this, "spreadsheet_project" );
    project->addObject(this);
    QSInterpreter* interpreter = project->interpreter();

    project->load( "Spreadsheet.qsa" );
#endif

    connect(table,SIGNAL(rowResized(int,int,int)),this,SLOT(resized()));
    connect(table,SIGNAL(columnResized(int,int,int)),this,SLOT(resized()));
}

#ifdef QSA

// Prototype QSA support methods

void Spreadsheet::saveScripts()
{
    project->save("Spreadsheet.qsa");
}

void Spreadsheet::testScripts()
{
    QStringList list = project->interpreter()->functions();

    for (QStringList::Iterator it = list.begin();
         it != list.end(); ++it)
    {
        cout << *it << endl;
    }

    // Hardcoded here, call function "sum" with specified args

    QList<QVariant> args;

    args.append(1);
    args.append(1);

    // call the function
    project->interpreter()->call("sum", args); //QValueList<QVariant>() );

    QSScript* script = project->script("Spreadsheet.qs");

    if (script)
        cout << script->code() << endl;
    else
        cout << "No script by that name" << endl;
}

static QSWorkbench *spreadsheet_ide = 0;

void Spreadsheet::showQSAWorkbench()
{

    if (!spreadsheet_ide )
    {
        spreadsheet_ide = new QSWorkbench( project, this, "qside" );

    }

    spreadsheet_ide->open();
}

#else

// Warn user that there is no QSA support compiled in

void Spreadsheet::showQSAWorkbench()
{
    QMessageBox::warning(0, tr("No QSA support!"),
                         tr("Sorry, no QSA support compiled in"),
                         QMessageBox::Ok, QMessageBox::NoButton);
}

void Spreadsheet::testScripts()
{
    QMessageBox::warning(0, tr("No QSA support!"),
                         tr("Sorry, no QSA support compiled in"),
                         QMessageBox::Ok, QMessageBox::NoButton);
}

void Spreadsheet::saveScripts()
{
    QMessageBox::warning(0, tr("No QSA support!"),
                         tr("Sorry, no QSA support compiled in"),
                         QMessageBox::Ok, QMessageBox::NoButton);
}

#endif

/*---------------------------------------------------------------------------
 *  Function:  setCurrencyFormatter
 *
 *  Description:
 *    Set a formatter on the selected cells do display the values
 *    in dollar value ($ XX.YY)
 */

void Spreadsheet::setCurrencyFormatter()
{
    this->getSelectedRegion();

    if ( (startSelectedRow > -1 ) && (startSelectedColumn > -1) )
      {
        int i, j;

        QicsDataItemCurrencyFormatter* currency =
            new QicsDataItemCurrencyFormatter();

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
                table->cellRef(i,j).setFormatter(currency);

      }

}

/*---------------------------------------------------------------------------
 *  Function:  getCellValue
 *
 *  Description:
 *    Return the value of cell[row][col]
 */

QString Spreadsheet::getCellValue(int row, int col)
{
    return dm->itemString(row, col);
}

/*---------------------------------------------------------------------------
 *  Function:  setCellValue
 *
 *  Description:
 *    Set cell[row][col] = value
 */

void Spreadsheet::setCellValue(int row, int col, int value)
{
    dm->setItem(row, col, value);
}

/*---------------------------------------------------------------------------
 *  Function:  cellLineUpdate()
 *
 *  Description:
 *    When a value is entered in the cellLineEdit and a cell is selected in
 *    the table, store the data element as a new data item.
 */

void Spreadsheet::cellLineUpdate()
{

    this->getSelectedRegion();

    if ( (startSelectedRow > -1 ) && (startSelectedColumn > -1) )
    {
        // OK, we got a selected cell and some data.  Time to
        // put it into the data model

        // temp var because they are easier to type
        int row = startSelectedRow;
        int col = startSelectedColumn;

    bool ok;

    // Try to convert to int
    int i = cellLineEdit->text().toInt(&ok);

    if (ok)
      {
        dm->setItem(row, col, i);
        return;
      }

    // Try to convert to float
    float f = cellLineEdit->text().toFloat(&ok);

    if (ok)
      {
        dm->setItem(row, col, f);
        return;
      }


    dm->setItem(row, col, cellLineEdit->text());
    }

}

void Spreadsheet::selectFont(int combo)
{
   Q_UNUSED(combo);

   QString family = fontFamilyCombo->currentText();
   QString size = fontSizeCombo->currentText();

    // If cells are selected, set their display font

    this->getSelectedRegion();

    if (startSelectedRow > -1)
    {
      QFontDatabase fdb;
      bool ok;

      QFont currentFont =
    table->cellRef(startSelectedRow, startSelectedColumn).font();

      QFont font = fdb.font(family, fdb.styleString(currentFont),
                size.toInt(&ok));

        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
                table->cellRef(i,j).setFont(font);
    }

}

/*---------------------------------------------------------------------------
 *  Function:  formatBackgroundColor
 *
 *  Description:
 *    Bring up the color dialog, select a color, apply it to the selected
 *    region as the background color
 */

void Spreadsheet::formatBackgroundColor()
{
    QColor color = QColorDialog::getColor();

    if (! color.isValid())
    {
        return;
    }

    // If cells are selected, set their display font

    this->getSelectedRegion();

    if (startSelectedRow > -1)
    {
        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
                table->cellRef(i,j).setBackgroundColor(color);
    }
}

/*---------------------------------------------------------------------------
 *  Function:  formatForegroundColor
 *
 *  Description:
 *    Bring up the color dialog, select a color, apply it to the selected
 *    region as the foreground color
 */

void Spreadsheet::formatForegroundColor()
{
    QColor color = QColorDialog::getColor();

    if (! color.isValid())
    {
        return;
    }

    // If cells are selected, set their display font

    this->getSelectedRegion();

    if (startSelectedRow > -1)
    {
        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
                table->cellRef(i,j).setForegroundColor(color);
    }
}

/*---------------------------------------------------------------------------
 *  Function:  formatFont
 *
 *  Description:
 *    Bring up the font dialog, select a font, apply it to the selected region
 */

void Spreadsheet::formatFont()
{
    bool ok;

    // Select a font

    QFont font = QFontDialog::getFont(&ok, QFont("Helvetica", 10), this);

    if (!ok )
    {
        return;
    }

    // If cells are selected, set their display font

    this->getSelectedRegion();

    if (startSelectedRow > -1)
    {
        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
                table->cellRef(i,j).setFont(font);
    }

}

/*---------------------------------------------------------------------------
 *  Function:  updateSelection
 *
 *  Description:
 *    A cell was selected, so update the state of the toolbar pieces.
 */

void Spreadsheet::updateSelection(bool in_progress)
{
    if (in_progress)
    {
    return;
    }

    this->getSelectedRegion();


    if ( (startSelectedRow > -1 ) && (startSelectedColumn > -1) )
    {
        QFont font = table->cellRef(startSelectedRow, startSelectedColumn).font();
        setFontCombos(font);

        if (font.bold())
        {
            boldAction->setChecked(true);
        }
        else
        {
            // Is on, turn off (not bold)
            boldAction->setChecked(false);
        }

        if (font.italic())
        {
            italicAction->setChecked(true);
        }
        else
        {
            // Is on, turn off (not bold)
            italicAction->setChecked(false);
        }

        if (font.underline())
        {
            underlineAction->setChecked(true);
        }
        else
        {
            // Is on, turn off (not bold)
            underlineAction->setChecked(false);
        }

        int alignment = table->cellRef(startSelectedRow, startSelectedColumn).alignment();

        switch (alignment)
        {

        case Qt::AlignLeft:
            textLeftAction->setChecked(true);
            textRightAction->setChecked(false);
            textCenterAction->setChecked(false);
            break;

        case Qt::AlignRight:
            textLeftAction->setChecked(false);
            textRightAction->setChecked(true);
            textCenterAction->setChecked(false);
            break;

        case Qt::AlignHCenter:
            textLeftAction->setChecked(false);
            textRightAction->setChecked(false);
            textCenterAction->setChecked(true);
            break;

        default:
            textLeftAction->setChecked(false);
            textRightAction->setChecked(false);
            textCenterAction->setChecked(false);
            break;
        }

        if (dm->item(startSelectedRow, startSelectedColumn) == NULL)
        {
            cellLineEdit->setText("");
            return;
        }

        QicsCell* cell = table->cell(startSelectedRow, startSelectedColumn, true);

        if (cell->dataValue())
        {
            QString cellval = cell->dataValue()->string();

            cellLineEdit->setText(cellval);
        }
    }

}

/*---------------------------------------------------------------------------
 *  Function:  insertColumn
 *
 *  Description:
 *    Add a column to the table before the currently selected column
 */

void Spreadsheet::insertColumn()
{

    this->getSelectedRegion();

    if (startSelectedColumn > -1)
    {
        table->insertColumn(startSelectedColumn);
    }

}

/*---------------------------------------------------------------------------
 *  Function:  insertRow
 *
 *  Description:
 *    Add a row to the table before the currently selected row
 */

void Spreadsheet::insertRow()
{

    this->getSelectedRegion();

    if (startSelectedRow > -1)
    {
        table->insertRow(startSelectedRow);
    }

}


/*---------------------------------------------------------------------------
 *  Function:  setFontCombos
 *
 *  Description:
 *    Given a font, set the fontFamilyCombo to show it, set the fontSizeCombo
 *    to contain valid sizes for that font, and then show the correct
 *    font size.
 */

void Spreadsheet::setFontCombos(const QFont& font)
{
    // Set font family
    fontFamilyCombo->setEditText(font.family());

    QFontDatabase fdb;
    QList<int> sizes = fdb.pointSizes(font.family());

    // Clear the sizes combo, fill it with valid sizes based in family

    fontSizeCombo->clear();

    if (sizes.begin() != sizes.end())
      {
          for (QList<int>::Iterator pts = sizes.begin(); pts != sizes.end(); ++pts)
          {
             fontSizeCombo->addItem(QString::number(*pts));
          }
          fontSizeCombo->setEditText(QString::number(font.pointSize()));
     }
}

/*---------------------------------------------------------------------------
 *  Function:  textAlignLeft
 *
 *  Description:
 *    Set the alignment value of the displayed cell to AlignLeft
 */

void Spreadsheet::textAlignLeft()
{

    if ( (startSelectedRow < 0) && (startSelectedColumn < 0))
    {
        return;
    }

    if (startSelectedRow > -1)
    {
        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
            {
                table->cellRef(i, j).setAlignment(Qt::AlignLeft);
            }
    }

    textRightAction->setChecked(false);
    textCenterAction->setChecked(false);

}

/*---------------------------------------------------------------------------
 *  Function:  textAlignCenter
 *
 *  Description:
 *    Set the alignment value of the displayed cell to AlignHCenter
 */

void Spreadsheet::textAlignCenter()
{

    if ( (startSelectedRow < 0) && (startSelectedColumn < 0))
    {
        return;
    }

    if (startSelectedRow > -1)
    {
        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
            {
                table->cellRef(i, j).setAlignment(Qt::AlignHCenter);
            }
    }

    textLeftAction->setChecked(false);
    textRightAction->setChecked(false);

}

/*---------------------------------------------------------------------------
 *  Function:  textAlignRight
 *
 *  Description:
 *    Set the alignment value of the displayed cell to AlignRight
 */

void Spreadsheet::textAlignRight()
{

    if ( (startSelectedRow < 0) && (startSelectedColumn < 0))
    {
        return;
    }

    if (startSelectedRow > -1)
    {
        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
            {
                table->cellRef(i, j).setAlignment(Qt::AlignRight);
            }
    }

    textLeftAction->setChecked(false);
    textCenterAction->setChecked(false);

}

/*---------------------------------------------------------------------------
 *  Function:  textBold
 *
 *  Description:
 *    Toggle the boldness state of whatever cells are selected
 */

void Spreadsheet::textBold()
{

    if ( (startSelectedRow < 0) && (startSelectedColumn < 0))
    {
        return;
    }

    bool on = boldAction->isChecked();

    if (startSelectedRow > -1)
    {
        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
            {
                QFont f = table->cellRef(i, j).font();
                f.setBold(on);
                table->cellRef(i, j).setFont(f);
            }
    }
}

/*---------------------------------------------------------------------------
 *  Function:  textItalic
 *
 *  Description:
 *    Toggle the italic-ness state of whatever cells are selected
 */

void Spreadsheet::textItalic()
{

    if ( (startSelectedRow < 0) && (startSelectedColumn < 0))
    {
        return;
    }

    bool on = italicAction->isChecked();

    if (startSelectedRow > -1)
    {
        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
            {
                QFont f = table->cellRef(i, j).font();
                f.setItalic(on);
                table->cellRef(i, j).setFont(f);
            }
    }
}

/*---------------------------------------------------------------------------
 *  Function:  textUnderline
 *
 *  Description:
 *    Toggle the underline-ed-ness state of whatever cells are selected
 */

void Spreadsheet::textUnderline()
{

    if ( (startSelectedRow < 0) && (startSelectedColumn < 0))
    {
        return;
    }

    bool on = underlineAction->isChecked();

    if (startSelectedRow > -1)
    {
        int i, j;

        for (i = startSelectedRow; i < endSelectedRow; i++)
            for (j = startSelectedColumn; j < endSelectedColumn; j++)
            {
                QFont f = table->cellRef(i, j).font();
                f.setUnderline(on);
                table->cellRef(i, j).setFont(f);
            }
    }
}

/*---------------------------------------------------------------------------
 *  Function:  openFile
 *
 *  Description:
 *    Protected slot, bring up a QFileDialog to select a file, then load it.
 */

void Spreadsheet::openFile()
{
    QString fname =
        QFileDialog::getOpenFileName();

    if (fname != QString::null)
    {
        fileName = fname;
        loadFile(fileName);
    }

}

/*---------------------------------------------------------------------------
 *  Function:  loadFile
 *
 *  Description:
 *     Load a Comma Delimited File into the data table
 */

void Spreadsheet::loadFile(QString fname)
{
    // Create the stream from the file, read into data model
    QFile file(fname);

    if (file.open(QIODevice::ReadOnly))
    {
        QTextStream stream(&file);

        dm->readASCII(stream, ',');
    }
}

/*---------------------------------------------------------------------------
 *  Function:  saveFile
 *
 *  Description:
 *    Protected slot, save data to the current file name
 */

void Spreadsheet::saveFile()
{

    if (fileName != QString::null)
    {
        writeFile(fileName);
    }
}

/*---------------------------------------------------------------------------
 *  Function:  saveFileAs
 *
 *  Description:
 *    Protected slot, bring up a QFileDialog to select a file, then save to it.
 */

void Spreadsheet::saveFileAs()
{
    QString fname =
        QFileDialog::getSaveFileName();

    if (fname != QString::null)
    {
        fileName = fname;
        writeFile(fileName);
    }
}

/*---------------------------------------------------------------------------
 *  Function:  writeFile
 *
 *  Description:
 *     Save a Comma Delimited File from the data table
 */

void Spreadsheet::writeFile(QString fname)
{

    // Create the stream from the file, read into data model
    QFile file(fname);

    if (file.open(QIODevice::WriteOnly))
    {
        QTextStream stream(&file);

        dm->writeASCII(stream, ',', 0, 0, 10, 10);
    }

}

/*---------------------------------------------------------------------------
 *  Function:  fileNew
 *
 *  Description:
 *     Clear out all the data currently displayed in the table.
 */

void Spreadsheet::fileNew()
{
    // To be implemented
    qDebug("To be implemented");
}

/*---------------------------------------------------------------------------
 *  Function:  copy
 *
 *  Description:
 *     Calls the table's copy operation to place data into the QClipboard
 *     owned by qApp.
 */

void Spreadsheet::copy()
{
    table->copy();
}

/*---------------------------------------------------------------------------
 *  Function:  cut
 *
 *  Description:
 *     Calls the table's cut operation to place data into the QClipboard
 *     owned by qApp and remove it from the visible table area
 */

void Spreadsheet::cut()
{
    table->cut();
}

/*---------------------------------------------------------------------------
 *  Function:  paste
 *
 *  Description:
 *     Calls the table's paste operation to retrieve cells from the QClipboard
 *     owned by qApp and paste them at the current cell.
 */

void Spreadsheet::paste()
{
    table->paste();
}


/*---------------------------------------------------------------------------
 *  Function:  getSelectedRegion
 *
 *  Description:
 *     Query the table, find the start and end row/column of the currently
 *     selected region, if any.
 */

void Spreadsheet::getSelectedRegion()
{
    QicsSelection selection;
    QicsSelectionList *list = table->selectionList();

    // Get selected boundry

    if (list != NULL)
    {
        if (list->begin() != list->end())
        {
            selection = *(list->begin());

            startSelectedRow = selection.anchorRow();
            startSelectedColumn = selection.anchorColumn();
        }
    }
    else
    {
        startSelectedRow = startSelectedColumn = -1;  // reset flags
    }

    delete list;

    int row = selection.endRow();
    if (row > dm->lastRow())
        row = dm->lastRow() + 1;
    else
        row++;

    int col = selection.endColumn();
    if (col > dm->lastColumn())
        col = dm->lastColumn() + 1;
    else
        col++;

    endSelectedRow = row;
    endSelectedColumn = col;

}

/*---------------------------------------------------------------------------
 *  Function:  sortAscending
 *
 *  Description:
 *     Sort the table by the selected column in ascending order
 */

void Spreadsheet::sortAscending()
{
    QicsSelectionList *list = table->selectionList();
    QicsSelectionList::const_iterator iter;
    QVector<int> selectedCols;

    for (iter = list->begin(); iter < list->end(); ++iter)
        selectedCols << (*iter).anchorColumn();

    if (selectedCols.size() <= 0) selectedCols << 0;
    table->sortRows(selectedCols, Qics::Ascending);
}

/*---------------------------------------------------------------------------
 *  Function:  sortDescending
 *
 *  Description:
 *     Sort the table by the selected column in descending order
 */

void Spreadsheet::sortDescending()
{
    QicsSelectionList *list = table->selectionList();
    QicsSelectionList::const_iterator iter;
    QVector<int> selectedCols;

    for (iter = list->begin(); iter < list->end(); ++iter)
        selectedCols << (*iter).anchorColumn();

    if (selectedCols.size() <= 0) selectedCols << 0;
    table->sortRows(selectedCols, Qics::Descending);
}


void Spreadsheet::resized()
{
}


/*---------------------------------------------------------------------------
 *  Function:  addSpan
 *
 *  Description:
 *     Adds span to selected cells
 */


void Spreadsheet::addSpan()
{
        QicsSelectionList *slist = table->selectionList();
        if(slist)
        {
                QicsSelectionList::const_iterator iter;

                for (iter = slist->begin(); iter != slist->end(); ++iter)
                {
                    const QicsSelection &sel = *iter;
                    int bottom_row = sel.numRows();
                    int right_column = sel.numColumns();

                    if(sel.bottomRow() == Qics::QicsLAST_ROW)
                        bottom_row = table->dataModel()->numRows();
                    if(sel.rightColumn() == Qics::QicsLAST_COLUMN)
                        right_column = table->dataModel()->numColumns();

                    table->addCellSpan(QicsSpan(sel.topRow(),sel.leftColumn(),bottom_row,right_column));
                }
        }
}

/*---------------------------------------------------------------------------
 *  Function:  removeSpan
 *
 *  Description:
 *     Removes span from selected cells
 */

void Spreadsheet::removeSpan()
{
        QicsSelectionList *slist = table->selectionList();
        if(slist)
        {
                QicsSelectionList::const_iterator iter;

                for (iter = slist->begin(); iter != slist->end(); ++iter)
                {
                    const QicsSelection &sel = *iter;
                    table->removeCellSpan(sel.topRow(),sel.leftColumn());
                }
        }
}

/*---------------------------------------------------------------------------
 *  Function print
 *
 *  Description:
 *     prints current table
 */
#ifdef CREATE_OBJS_WITH_QICSTABLE

void Spreadsheet::print()
{
    QPrinter* printer = new QPrinter;
    QPrintDialog printDialog(printer, this);
    if (printDialog.exec() == QDialog::Accepted) {
        // print ...
        table->print( printer );
    }
}
#endif



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

    Spreadsheet* ss = new Spreadsheet(0);

    ss->show();

    return qapp.exec();
}



All trademarks and copyrights on this page are properties of their respective owners.
The rest is copyright 1999-2006 Integrated Computer Solutions, Inc.