~oif-team/ubuntu/natty/qt4-x11/xi2.1

« back to all changes in this revision

Viewing changes to demos/spreadsheet/main.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Adam Conrad
  • Date: 2005-08-24 04:09:09 UTC
  • Revision ID: james.westby@ubuntu.com-20050824040909-xmxe9jfr4a0w5671
Tags: upstream-4.0.0
ImportĀ upstreamĀ versionĀ 4.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/****************************************************************************
 
2
**
 
3
** Copyright (C) 1992-2005 Trolltech AS. All rights reserved.
 
4
**
 
5
** This file is part of the demonstration applications of the Qt Toolkit.
 
6
**
 
7
** This file may be distributed under the terms of the Q Public License
 
8
** as defined by Trolltech AS of Norway and appearing in the file
 
9
** LICENSE.QPL included in the packaging of this file.
 
10
**
 
11
** This file may be distributed and/or modified under the terms of the
 
12
** GNU General Public License version 2 as published by the Free Software
 
13
** Foundation and appearing in the file LICENSE.GPL included in the
 
14
** packaging of this file.
 
15
**
 
16
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
 
17
**   information about Qt Commercial License Agreements.
 
18
** See http://www.trolltech.com/qpl/ for QPL licensing information.
 
19
** See http://www.trolltech.com/gpl/ for GPL licensing information.
 
20
**
 
21
** Contact info@trolltech.com if any conditions of this licensing are
 
22
** not clear to you.
 
23
**
 
24
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 
25
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 
26
**
 
27
****************************************************************************/
 
28
 
 
29
#include <QtGui>
 
30
 
 
31
static QString encode_pos(int row, int col) {
 
32
    return QString(col + 'A') + QString(row + '0');
 
33
}
 
34
 
 
35
static void decode_pos(const QString &pos, int *row, int *col)
 
36
{
 
37
    *col = pos.at(0).toLatin1() - 'A';
 
38
    *row = pos.at(1).toLatin1() - '0';
 
39
}
 
40
 
 
41
class SpreadSheetItem : public QTableWidgetItem
 
42
{
 
43
public:
 
44
    SpreadSheetItem();
 
45
    SpreadSheetItem(const QString &text);
 
46
 
 
47
    QTableWidgetItem *clone() const;
 
48
 
 
49
    QVariant data(int role) const;
 
50
    void setData(int role, const QVariant &value);
 
51
    QVariant display() const;
 
52
 
 
53
    inline QString formula() const
 
54
        { return QTableWidgetItem::data(Qt::DisplayRole).toString(); }
 
55
 
 
56
    QPoint convertCoords(const QString coords) const;
 
57
 
 
58
private:
 
59
    mutable bool isResolving;
 
60
};
 
61
 
 
62
SpreadSheetItem::SpreadSheetItem()
 
63
    : QTableWidgetItem(), isResolving(false) {}
 
64
 
 
65
SpreadSheetItem::SpreadSheetItem(const QString &text)
 
66
    : QTableWidgetItem(text), isResolving(false) {}
 
67
 
 
68
QTableWidgetItem *SpreadSheetItem::clone() const
 
69
{
 
70
    SpreadSheetItem *item = new SpreadSheetItem();
 
71
    *item = *this;
 
72
    return item;
 
73
}
 
74
 
 
75
QVariant SpreadSheetItem::data(int role) const
 
76
{
 
77
    if (role == Qt::EditRole || role == Qt::StatusTipRole)
 
78
        return formula();
 
79
 
 
80
    if (role == Qt::DisplayRole)
 
81
        return display();
 
82
 
 
83
    QString t = display().toString();
 
84
    bool isNumber = false;
 
85
    int number = t.toInt(&isNumber);
 
86
 
 
87
    if (role == Qt::TextColorRole) {
 
88
        if (!isNumber)
 
89
            return qVariantFromValue(QColor(Qt::black));
 
90
        else if (number < 0)
 
91
            return qVariantFromValue(QColor(Qt::red));
 
92
        return qVariantFromValue(QColor(Qt::blue));
 
93
    }
 
94
 
 
95
    if (role == Qt::TextAlignmentRole)
 
96
        if (!t.isEmpty() && (t.at(0).isNumber() || t.at(0) == '-'))
 
97
            return (int)(Qt::AlignRight | Qt::AlignVCenter);
 
98
 
 
99
    return QTableWidgetItem::data(role);
 
100
}
 
101
 
 
102
void SpreadSheetItem::setData(int role, const QVariant &value)
 
103
{
 
104
    QTableWidgetItem::setData(role, value);
 
105
    if (tableWidget())
 
106
        tableWidget()->viewport()->update();
 
107
}
 
108
 
 
109
QVariant SpreadSheetItem::display() const
 
110
{
 
111
    // check if the string is actially a formula or not
 
112
    QString formula = this->formula();
 
113
    QStringList list = formula.split(' ');
 
114
    if (list.count() != 3)
 
115
        return formula; // its a normal string
 
116
 
 
117
    QString op = list.at(0).toLower();
 
118
    QPoint one = convertCoords(list.at(1));
 
119
    QPoint two = convertCoords(list.at(2));
 
120
 
 
121
    const QTableWidgetItem *start = tableWidget()->item(one.y(), one.x());
 
122
    QTableWidgetItem *end = tableWidget()->item(two.y(), two.x());
 
123
 
 
124
    if (!start || !end)
 
125
        return "Error: Item does not exist!";
 
126
 
 
127
    // avoid circular dependencies
 
128
    if (isResolving)
 
129
        return QVariant();
 
130
    isResolving = true;
 
131
 
 
132
    QVariant result;
 
133
    if (op == "sum") {
 
134
        int sum = 0;
 
135
        for (int r = tableWidget()->row(start); r <= tableWidget()->row(end); ++r) {
 
136
            for (int c = tableWidget()->column(start); c <= tableWidget()->column(end); ++c) {
 
137
                const QTableWidgetItem *tableItem = tableWidget()->item(r, c);
 
138
                if (tableItem && tableItem != this)
 
139
                    sum += tableItem->text().toInt();
 
140
            }
 
141
        }
 
142
        result = sum;
 
143
    } else if (op == "+") {
 
144
        printf("+, %s, %s\n", qPrintable(start->text()), qPrintable(end->text()));
 
145
        result = (start->text().toInt() + end->text().toInt());
 
146
    } else if (op == "-") {
 
147
        result = (start->text().toInt() - end->text().toInt());
 
148
    } else if (op == "*") {
 
149
        result = (start->text().toInt() * end->text().toInt());
 
150
    } else if (op == "/") {
 
151
        if (end->text().toInt() == 0)
 
152
            result = QString("nan");
 
153
        else
 
154
            result = (start->text().toInt() / end->text().toInt());
 
155
    } else {
 
156
        result = "Error: Operation does not exist!";
 
157
    }
 
158
 
 
159
    isResolving = false;
 
160
    return result;
 
161
}
 
162
 
 
163
QPoint SpreadSheetItem::convertCoords(const QString coords) const
 
164
{
 
165
    int r = 0;
 
166
    int c = coords.at(0).toUpper().toAscii() - 'A';
 
167
    for (int i = 1; i < coords.count(); ++i) {
 
168
        r *= 10;
 
169
        r += coords.at(i).digitValue();
 
170
    }
 
171
    return QPoint(c, r);
 
172
}
 
173
 
 
174
//   Here we subclass QTableWidget to change the selection behavior to only select with the left mouse button
 
175
//   (so we keep the selection when opening the context menu on an item).
 
176
 
 
177
class SpreadSheetTable : public QTableWidget
 
178
{
 
179
    Q_OBJECT
 
180
public:
 
181
    SpreadSheetTable(int rows, int columns, QWidget *parent) :
 
182
        QTableWidget(rows, columns, parent) {}
 
183
 
 
184
    QItemSelectionModel::SelectionFlags selectionCommand(const QModelIndex &index,
 
185
                                                         const QEvent *event) const;
 
186
};
 
187
 
 
188
QItemSelectionModel::SelectionFlags SpreadSheetTable::selectionCommand(const QModelIndex &index,
 
189
                                                                       const QEvent *event) const
 
190
{
 
191
    const QMouseEvent *me = event && event->type() == QEvent::MouseButtonPress
 
192
                            ? static_cast<const QMouseEvent *>(event) : 0;
 
193
    if (me && (me->buttons() & Qt::RightButton || me->buttons() & Qt::MidButton))
 
194
        return QItemSelectionModel::NoUpdate;
 
195
    return QTableWidget::selectionCommand(index, event);
 
196
}
 
197
 
 
198
class SpreadSheet : public QMainWindow
 
199
{
 
200
    Q_OBJECT
 
201
public:
 
202
    SpreadSheet(int rows, int cols, QWidget *parent = 0);
 
203
 
 
204
public slots:
 
205
    void updateStatus(QTableWidgetItem *item);
 
206
    void updateColor(QTableWidgetItem *item);
 
207
    void updateLineEdit(QTableWidgetItem *item);
 
208
    void returnPressed();
 
209
    void selectColor();
 
210
    void selectFont();
 
211
    void clear();
 
212
    void showAbout();
 
213
 
 
214
    void actionSum();
 
215
    void actionSubtract();
 
216
    void actionAdd();
 
217
    void actionMultiply();
 
218
    void actionDivide();
 
219
 
 
220
protected:
 
221
    void setupContextMenu();
 
222
    void setupContents();
 
223
 
 
224
    void setupToolBar();
 
225
    void setupMenuBar();
 
226
    void createActions();
 
227
 
 
228
    void actionMath_helper(const QString &title, const QString &op);
 
229
    bool runInputDialog(const QString &title,
 
230
                        const QString &c1Text,
 
231
                        const QString &c2Text,
 
232
                        const QString &opText,
 
233
                        const QString &outText,
 
234
                        QString *cell1, QString *cell2, QString *outCell);
 
235
 
 
236
private:
 
237
    QToolBar *toolBar;
 
238
    QAction *colorAction;
 
239
    QAction *fontAction;
 
240
    QAction *firstSeparator;
 
241
    QAction *cell_sumAction;
 
242
    QAction *cell_addAction;
 
243
    QAction *cell_subAction;
 
244
    QAction *cell_mulAction;
 
245
    QAction *cell_divAction;
 
246
    QAction *secondSeparator;
 
247
    QAction *clearAction;
 
248
    QAction *aboutSpreadSheet;
 
249
    QAction *exitAction;
 
250
 
 
251
    QLabel *cellLabel;
 
252
    QTableWidget *table;
 
253
    QLineEdit *formulaInput;
 
254
};
 
255
 
 
256
SpreadSheet::SpreadSheet(int rows, int cols, QWidget *parent)
 
257
    : QMainWindow(parent)
 
258
{
 
259
    addToolBar(toolBar = new QToolBar());
 
260
    formulaInput = new QLineEdit();
 
261
 
 
262
    cellLabel = new QLabel(toolBar);
 
263
    cellLabel->setMinimumSize(80, 0);
 
264
 
 
265
    toolBar->addWidget(cellLabel);
 
266
    toolBar->addWidget(formulaInput);
 
267
 
 
268
    table = new SpreadSheetTable(rows, cols, this);
 
269
    for (int c = 0; c < cols; ++c) {
 
270
        QString character(QChar('A' + c));
 
271
        table->setHorizontalHeaderItem(c, new QTableWidgetItem(character));
 
272
        table->horizontalHeaderItem(c)->setTextAlignment(Qt::AlignCenter);
 
273
    }
 
274
    table->setItemPrototype(table->item(rows - 1, cols - 1));
 
275
 
 
276
    createActions();
 
277
 
 
278
    updateColor(0);
 
279
    setupToolBar();
 
280
    setupMenuBar();
 
281
    setupContextMenu();
 
282
    setupContents();
 
283
    setCentralWidget(table);
 
284
 
 
285
    statusBar();
 
286
    connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)),
 
287
            this, SLOT(updateStatus(QTableWidgetItem*)));
 
288
    connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)),
 
289
            this, SLOT(updateColor(QTableWidgetItem*)));
 
290
    connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)),
 
291
            this, SLOT(updateLineEdit(QTableWidgetItem*)));
 
292
    connect(table, SIGNAL(itemChanged(QTableWidgetItem*)),
 
293
            this, SLOT(updateStatus(QTableWidgetItem*)));
 
294
    connect(formulaInput, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
 
295
    connect(table, SIGNAL(itemChanged(QTableWidgetItem*)),
 
296
            this, SLOT(updateLineEdit(QTableWidgetItem*)));
 
297
 
 
298
    setWindowTitle(tr("Spreadsheet"));
 
299
}
 
300
 
 
301
void SpreadSheet::createActions()
 
302
{
 
303
    cell_sumAction = new QAction(tr("Sum"), this);
 
304
    connect(cell_sumAction, SIGNAL(triggered()), this, SLOT(actionSum()));
 
305
 
 
306
    cell_addAction = new QAction(tr("&Add"), this);
 
307
    cell_addAction->setShortcut(Qt::CTRL | Qt::Key_Plus);
 
308
    connect(cell_addAction, SIGNAL(triggered()), this, SLOT(actionAdd()));
 
309
 
 
310
    cell_subAction = new QAction(tr("&Subtract"), this);
 
311
    cell_subAction->setShortcut(Qt::CTRL | Qt::Key_Minus);
 
312
    connect(cell_subAction, SIGNAL(triggered()), this, SLOT(actionSubtract()));
 
313
 
 
314
    cell_mulAction = new QAction(tr("&Multiply"), this);
 
315
    cell_mulAction->setShortcut(Qt::CTRL | Qt::Key_multiply);
 
316
    connect(cell_mulAction, SIGNAL(triggered()), this, SLOT(actionMultiply()));
 
317
 
 
318
    cell_divAction = new QAction(tr("&Divide"), this);
 
319
    cell_divAction->setShortcut(Qt::CTRL | Qt::Key_division);
 
320
    connect(cell_divAction, SIGNAL(triggered()), this, SLOT(actionDivide()));
 
321
 
 
322
    fontAction = new QAction(tr("Font..."), this);
 
323
    fontAction->setShortcut(Qt::CTRL|Qt::Key_F);
 
324
    connect(fontAction, SIGNAL(triggered()), this, SLOT(selectFont()));
 
325
 
 
326
    colorAction = new QAction(QPixmap(16, 16), tr("Background &Color"), this);
 
327
    connect(colorAction, SIGNAL(triggered()), this, SLOT(selectColor()));
 
328
 
 
329
    clearAction = new QAction(tr("Clear"), this);
 
330
    clearAction->setShortcut(Qt::Key_Delete);
 
331
    connect(clearAction, SIGNAL(triggered()), this, SLOT(clear()));
 
332
 
 
333
    aboutSpreadSheet = new QAction(tr("About SpreadSheet"), this);
 
334
    connect(aboutSpreadSheet, SIGNAL(triggered()), this, SLOT(showAbout()));
 
335
 
 
336
    exitAction = new QAction(tr("E&xit"), this);
 
337
    connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
 
338
 
 
339
    firstSeparator = new QAction(this);
 
340
    firstSeparator->setSeparator(true);
 
341
 
 
342
    secondSeparator = new QAction(this);
 
343
    secondSeparator->setSeparator(true);
 
344
 
 
345
 
 
346
}
 
347
 
 
348
void SpreadSheet::setupMenuBar()
 
349
{
 
350
    QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
 
351
    fileMenu->addAction(exitAction);
 
352
 
 
353
    QMenu *cellMenu = menuBar()->addMenu(tr("&Cell"));
 
354
    cellMenu->addAction(cell_addAction);
 
355
    cellMenu->addAction(cell_subAction);
 
356
    cellMenu->addAction(cell_mulAction);
 
357
    cellMenu->addAction(cell_divAction);
 
358
    cellMenu->addAction(cell_sumAction);
 
359
    cellMenu->addSeparator();
 
360
    cellMenu->addAction(colorAction);
 
361
    cellMenu->addAction(fontAction);
 
362
 
 
363
    menuBar()->addSeparator();
 
364
 
 
365
    QMenu *aboutMenu = menuBar()->addMenu(tr("&Help"));
 
366
    aboutMenu->addAction(aboutSpreadSheet);
 
367
}
 
368
 
 
369
void SpreadSheet::setupToolBar()
 
370
{
 
371
//     toolBar->addAction(cell_sumAction);
 
372
 
 
373
//     toolBar->addAction(firstSeparator);
 
374
//     toolBar->addAction(fontAction);
 
375
//     toolBar->addAction(colorAction);
 
376
//     toolBar->addAction(secondSeparator);
 
377
//     toolBar->addAction(clearAction);
 
378
}
 
379
 
 
380
void SpreadSheet::updateStatus(QTableWidgetItem *item)
 
381
{
 
382
    if (item && item == table->currentItem()) {
 
383
        statusBar()->showMessage(item->data(Qt::StatusTipRole).toString(), 1000);
 
384
        cellLabel->setText("Cell: (" + encode_pos(table->row(item), table->column(item)) + ")");
 
385
    }
 
386
}
 
387
 
 
388
void SpreadSheet::updateColor(QTableWidgetItem *item)
 
389
{
 
390
    QPixmap pix(16, 16);
 
391
    QColor col;
 
392
    if (item)
 
393
        col = item->backgroundColor();
 
394
    if (!col.isValid())
 
395
        col = palette().base().color();
 
396
 
 
397
    QPainter pt(&pix);
 
398
    pt.fillRect(0, 0, 16, 16, col);
 
399
 
 
400
    QColor lighter = col.light();
 
401
    pt.setPen(lighter);
 
402
    QPoint lightFrame[] = { QPoint(0, 15), QPoint(0, 0), QPoint(15, 0) };
 
403
    pt.drawPolyline(lightFrame, 3);
 
404
 
 
405
    pt.setPen(col.dark());
 
406
    QPoint darkFrame[] = { QPoint(1, 15), QPoint(15, 15), QPoint(15, 1) };
 
407
    pt.drawPolyline(darkFrame, 3);
 
408
 
 
409
    pt.end();
 
410
 
 
411
    colorAction->setIcon(pix);
 
412
}
 
413
 
 
414
void SpreadSheet::updateLineEdit(QTableWidgetItem *item)
 
415
{
 
416
    if (item != table->currentItem())
 
417
        return;
 
418
    if (item)
 
419
        formulaInput->setText(item->data(Qt::EditRole).toString());
 
420
    else
 
421
        formulaInput->clear();
 
422
}
 
423
 
 
424
void SpreadSheet::returnPressed()
 
425
{
 
426
    QString text = formulaInput->text();
 
427
    int row = table->currentRow();
 
428
    int col = table->currentColumn();
 
429
    QTableWidgetItem *item = table->item(row, col);
 
430
    if (!item)
 
431
        table->setItem(row, col, new SpreadSheetItem(text));
 
432
    else
 
433
        item->setData(Qt::EditRole, text);
 
434
    table->viewport()->update();
 
435
}
 
436
 
 
437
void SpreadSheet::selectColor()
 
438
{
 
439
    QTableWidgetItem *item = table->currentItem();
 
440
    QColor col = item ? item->backgroundColor() : table->palette().base().color();
 
441
    col = QColorDialog::getColor(col, this);
 
442
    if (!col.isValid())
 
443
        return;
 
444
 
 
445
    QList<QTableWidgetItem*> selected = table->selectedItems();
 
446
    if (selected.count() == 0)
 
447
        return;
 
448
 
 
449
    foreach(QTableWidgetItem *i, selected)
 
450
        if (i) i->setBackgroundColor(col);
 
451
 
 
452
    updateColor(table->currentItem());
 
453
}
 
454
 
 
455
void SpreadSheet::selectFont()
 
456
{
 
457
    QList<QTableWidgetItem*> selected = table->selectedItems();
 
458
    if (selected.count() == 0)
 
459
        return;
 
460
    bool ok = false;
 
461
    QFont fnt = QFontDialog::getFont(&ok, font(), this);
 
462
    if (!ok)
 
463
        return;
 
464
    foreach(QTableWidgetItem *i, selected)
 
465
        if (i) i->setFont(fnt);
 
466
}
 
467
 
 
468
bool SpreadSheet::runInputDialog(const QString &title,
 
469
                                 const QString &c1Text,
 
470
                                 const QString &c2Text,
 
471
                                 const QString &opText,
 
472
                                 const QString &outText,
 
473
                                 QString *cell1, QString *cell2, QString *outCell)
 
474
{
 
475
    const QStringList rows = QStringList() << "0" << "1" << "2" << "3" << "4"
 
476
                                           << "5" << "6" << "7" << "8" << "9";
 
477
    const QStringList cols = QStringList() << "A" << "B" << "C" << "D" << "E" << "F";
 
478
 
 
479
    QDialog addDialog(this);
 
480
    addDialog.setWindowTitle(title);
 
481
 
 
482
    QGroupBox group(title, &addDialog);
 
483
    group.setMinimumSize(250, 100);
 
484
 
 
485
    QLabel cell1Label(c1Text, &group);
 
486
    QComboBox cell1RowInput(&group);
 
487
    cell1RowInput.addItems(rows);
 
488
    cell1RowInput.setCurrentIndex(cell1->at(1).toLatin1() - '0');
 
489
    QComboBox cell1ColInput(&group);
 
490
    cell1ColInput.addItems(cols);
 
491
    cell1ColInput.setCurrentIndex(cell1->at(0).toLatin1() - 'A');
 
492
 
 
493
    QLabel operatorLabel(opText, &group);
 
494
    operatorLabel.setAlignment(Qt::AlignHCenter);
 
495
 
 
496
    QLabel cell2Label(c2Text, &group);
 
497
    QComboBox cell2RowInput(&group);
 
498
    cell2RowInput.addItems(rows);
 
499
    cell2RowInput.setCurrentIndex(cell2->at(1).toLatin1() - '0');
 
500
    QComboBox cell2ColInput(&group);
 
501
    cell2ColInput.addItems(cols);
 
502
    cell2ColInput.setCurrentIndex(cell2->at(0).toLatin1() - 'A');
 
503
 
 
504
    QLabel equalsLabel("=", &group);
 
505
    equalsLabel.setAlignment(Qt::AlignHCenter);
 
506
 
 
507
    QLabel outLabel(outText, &group);
 
508
    QComboBox outRowInput(&group);
 
509
    outRowInput.addItems(rows);
 
510
    outRowInput.setCurrentIndex(outCell->at(1).toLatin1() - '0');
 
511
    QComboBox outColInput(&group);
 
512
    outColInput.addItems(cols);
 
513
    outColInput.setCurrentIndex(outCell->at(0).toLatin1() - 'A');
 
514
 
 
515
    QPushButton cancelButton(tr("Cancel"), &addDialog);
 
516
    connect(&cancelButton, SIGNAL(clicked()), &addDialog, SLOT(reject()));
 
517
 
 
518
    QPushButton okButton(tr("OK"), &addDialog);
 
519
    okButton.setDefault(true);
 
520
    connect(&okButton, SIGNAL(clicked()), &addDialog, SLOT(accept()));
 
521
 
 
522
    QHBoxLayout *buttonsLayout = new QHBoxLayout;
 
523
    buttonsLayout->addStretch(1);
 
524
    buttonsLayout->addWidget(&okButton);
 
525
    buttonsLayout->addSpacing(10);
 
526
    buttonsLayout->addWidget(&cancelButton);
 
527
 
 
528
    QVBoxLayout *dialogLayout = new QVBoxLayout(&addDialog);
 
529
    dialogLayout->addWidget(&group);
 
530
    dialogLayout->addStretch(1);
 
531
    dialogLayout->addItem(buttonsLayout);
 
532
 
 
533
    QHBoxLayout *cell1Layout = new QHBoxLayout;
 
534
    cell1Layout->addWidget(&cell1Label);
 
535
    cell1Layout->addSpacing(10);
 
536
    cell1Layout->addWidget(&cell1ColInput);
 
537
    cell1Layout->addSpacing(10);
 
538
    cell1Layout->addWidget(&cell1RowInput);
 
539
 
 
540
    QHBoxLayout *cell2Layout = new QHBoxLayout;
 
541
    cell2Layout->addWidget(&cell2Label);
 
542
    cell2Layout->addSpacing(10);
 
543
    cell2Layout->addWidget(&cell2ColInput);
 
544
    cell2Layout->addSpacing(10);
 
545
    cell2Layout->addWidget(&cell2RowInput);
 
546
 
 
547
    QHBoxLayout *outLayout = new QHBoxLayout;
 
548
    outLayout->addWidget(&outLabel);
 
549
    outLayout->addSpacing(10);
 
550
    outLayout->addWidget(&outColInput);
 
551
    outLayout->addSpacing(10);
 
552
    outLayout->addWidget(&outRowInput);
 
553
 
 
554
    QVBoxLayout *vLayout = new QVBoxLayout(&group);
 
555
    vLayout->addItem(cell1Layout);
 
556
    vLayout->addWidget(&operatorLabel);
 
557
    vLayout->addItem(cell2Layout);
 
558
    vLayout->addWidget(&equalsLabel);
 
559
    vLayout->addStretch(1);
 
560
    vLayout->addItem(outLayout);
 
561
 
 
562
    if (addDialog.exec()) {
 
563
        *cell1 = cell1ColInput.currentText() + cell1RowInput.currentText();
 
564
        *cell2 = cell2ColInput.currentText() + cell2RowInput.currentText();
 
565
        *outCell = outColInput.currentText() + outRowInput.currentText();
 
566
        return true;
 
567
    }
 
568
 
 
569
    return false;
 
570
}
 
571
 
 
572
 
 
573
void SpreadSheet::actionSum()
 
574
{
 
575
 
 
576
    int row_first = 0;
 
577
    int row_last = 0;
 
578
    int row_cur = 0;
 
579
 
 
580
    int col_first = 0;
 
581
    int col_last = 0;
 
582
    int col_cur = 0;
 
583
 
 
584
    QList<QTableWidgetItem*> selected = table->selectedItems();
 
585
    if (!selected.isEmpty()) {
 
586
        QTableWidgetItem *first = selected.first();
 
587
        QTableWidgetItem *last = selected.last();
 
588
        row_first = table->row(first);
 
589
        row_last = table->row(last);
 
590
        col_first = table->column(first);
 
591
        col_last = table->column(last);
 
592
    }
 
593
 
 
594
    QTableWidgetItem *current = table->currentItem();
 
595
    if (current) {
 
596
        row_cur = table->row(current);
 
597
        col_cur = table->column(current);
 
598
    }
 
599
 
 
600
    QString cell1 = encode_pos(row_first, col_first);
 
601
    QString cell2 = encode_pos(row_last, col_last);
 
602
    QString out = encode_pos(row_cur, col_cur);
 
603
 
 
604
 
 
605
    if (runInputDialog(tr("Sum cells"), tr("First cell:"), tr("Last cell:"),
 
606
                       QString("%1").arg(QChar(0x03a3)), tr("Output to:"),
 
607
                       &cell1, &cell2, &out)) {
 
608
        int row, col;
 
609
        decode_pos(out, &row, &col);
 
610
        table->item(row, col)->setText("sum " + cell1 + " " + cell2);
 
611
    }
 
612
}
 
613
 
 
614
 
 
615
void SpreadSheet::actionMath_helper(const QString &title, const QString &op)
 
616
{
 
617
    QString cell1 = "B1";
 
618
    QString cell2 = "B2";
 
619
    QString out = "B3";
 
620
 
 
621
    QTableWidgetItem *current = table->currentItem();
 
622
    if (current) {
 
623
        out = QString(table->currentColumn() + 'A') + QString(table->currentRow() + '0');
 
624
    }
 
625
 
 
626
    if (runInputDialog(title, tr("Cell 1"), tr("Cell 2"), op, tr("Output to:"),
 
627
                       &cell1, &cell2, &out)) {
 
628
        int row, col;
 
629
        decode_pos(out, &row, &col);
 
630
        table->item(row, col)->setText(op + " " + cell1 + " " + cell2);
 
631
    }
 
632
}
 
633
 
 
634
 
 
635
void SpreadSheet::actionAdd()
 
636
{
 
637
    actionMath_helper(tr("Addition"), "+");
 
638
}
 
639
 
 
640
void SpreadSheet::actionSubtract()
 
641
{
 
642
    actionMath_helper(tr("Subtraction"), "-");
 
643
}
 
644
 
 
645
void SpreadSheet::actionMultiply()
 
646
{
 
647
    actionMath_helper(tr("Multiplication"), "*");
 
648
}
 
649
 
 
650
void SpreadSheet::actionDivide()
 
651
{
 
652
    actionMath_helper(tr("Division"), "/");
 
653
}
 
654
 
 
655
void SpreadSheet::clear()
 
656
{
 
657
    foreach (QTableWidgetItem *i, table->selectedItems())
 
658
        i->setText("");
 
659
}
 
660
 
 
661
void SpreadSheet::setupContextMenu()
 
662
{
 
663
    addAction(cell_addAction);
 
664
    addAction(cell_subAction);
 
665
    addAction(cell_mulAction);
 
666
    addAction(cell_divAction);
 
667
    addAction(cell_sumAction);
 
668
    addAction(firstSeparator);
 
669
    addAction(colorAction);
 
670
    addAction(fontAction);
 
671
    addAction(secondSeparator);
 
672
    addAction(clearAction);
 
673
    setContextMenuPolicy(Qt::ActionsContextMenu);
 
674
}
 
675
 
 
676
void SpreadSheet::setupContents()
 
677
{
 
678
    QColor titleBackground(Qt::lightGray);
 
679
    QFont titleFont = table->font();
 
680
    titleFont.setBold(true);
 
681
 
 
682
    // column 0
 
683
    table->setItem(0, 0, new SpreadSheetItem("Item"));
 
684
    table->item(0, 0)->setBackgroundColor(titleBackground);
 
685
    table->item(0, 0)->setToolTip("This column shows the purchased item/service");
 
686
    table->item(0, 0)->setFont(titleFont);
 
687
    table->setItem(1, 0, new SpreadSheetItem("AirportBus"));
 
688
    table->setItem(2, 0, new SpreadSheetItem("Flight (Munich)"));
 
689
    table->setItem(3, 0, new SpreadSheetItem("Lunch"));
 
690
    table->setItem(4, 0, new SpreadSheetItem("Flight (LA)"));
 
691
    table->setItem(5, 0, new SpreadSheetItem("Taxi"));
 
692
    table->setItem(6, 0, new SpreadSheetItem("Dinner"));
 
693
    table->setItem(7, 0, new SpreadSheetItem("Hotel"));
 
694
    table->setItem(8, 0, new SpreadSheetItem("Flight (Oslo)"));
 
695
    table->setItem(9, 0, new SpreadSheetItem("Total:"));
 
696
    table->item(9, 0)->setFont(titleFont);
 
697
    table->item(9,0)->setBackgroundColor(Qt::lightGray);
 
698
    // column 1
 
699
    table->setItem(0, 1, new SpreadSheetItem("Price"));
 
700
    table->item(0, 1)->setBackgroundColor(titleBackground);
 
701
    table->item(0, 1)->setToolTip("This column shows the price of the purchase");
 
702
    table->item(0, 1)->setFont(titleFont);
 
703
    table->setItem(1, 1, new SpreadSheetItem("150"));
 
704
    table->setItem(2, 1, new SpreadSheetItem("2350"));
 
705
    table->setItem(3, 1, new SpreadSheetItem("-14"));
 
706
    table->setItem(4, 1, new SpreadSheetItem("980"));
 
707
    table->setItem(5, 1, new SpreadSheetItem("5"));
 
708
    table->setItem(6, 1, new SpreadSheetItem("120"));
 
709
    table->setItem(7, 1, new SpreadSheetItem("300"));
 
710
    table->setItem(8, 1, new SpreadSheetItem("1240"));
 
711
    table->setItem(9, 1, new SpreadSheetItem());
 
712
    table->item(9,1)->setBackgroundColor(Qt::lightGray);
 
713
    // column 2
 
714
    table->setItem(0, 2, new SpreadSheetItem("Currency"));
 
715
    table->item(0, 2)->setBackgroundColor(titleBackground);
 
716
    table->item(0, 2)->setToolTip("This column shows the currency");
 
717
    table->item(0, 2)->setFont(titleFont);
 
718
    table->setItem(1, 2, new SpreadSheetItem("NOK"));
 
719
    table->setItem(2, 2, new SpreadSheetItem("NOK"));
 
720
    table->setItem(3, 2, new SpreadSheetItem("EUR"));
 
721
    table->setItem(4, 2, new SpreadSheetItem("EUR"));
 
722
    table->setItem(5, 2, new SpreadSheetItem("USD"));
 
723
    table->setItem(6, 2, new SpreadSheetItem("USD"));
 
724
    table->setItem(7, 2, new SpreadSheetItem("USD"));
 
725
    table->setItem(8, 2, new SpreadSheetItem("USD"));
 
726
    table->setItem(9, 2, new SpreadSheetItem());
 
727
    table->item(9,2)->setBackgroundColor(Qt::lightGray);
 
728
    // column 3
 
729
    table->setItem(0, 3, new SpreadSheetItem("Ex.Rate"));
 
730
    table->item(0, 3)->setBackgroundColor(titleBackground);
 
731
    table->item(0, 3)->setToolTip("This column shows the exchange rate to NOK");
 
732
    table->item(0, 3)->setFont(titleFont);
 
733
    table->setItem(1, 3, new SpreadSheetItem("1"));
 
734
    table->setItem(2, 3, new SpreadSheetItem("1"));
 
735
    table->setItem(3, 3, new SpreadSheetItem("8"));
 
736
    table->setItem(4, 3, new SpreadSheetItem("8"));
 
737
    table->setItem(5, 3, new SpreadSheetItem("7"));
 
738
    table->setItem(6, 3, new SpreadSheetItem("7"));
 
739
    table->setItem(7, 3, new SpreadSheetItem("7"));
 
740
    table->setItem(8, 3, new SpreadSheetItem("7"));
 
741
    table->setItem(9, 3, new SpreadSheetItem());
 
742
    table->item(9,3)->setBackgroundColor(Qt::lightGray);
 
743
    // column 4
 
744
    table->setItem(0, 4, new SpreadSheetItem("NOK"));
 
745
    table->item(0, 4)->setBackgroundColor(titleBackground);
 
746
    table->item(0, 4)->setToolTip("This column shows the expenses in NOK");
 
747
    table->item(0, 4)->setFont(titleFont);
 
748
    table->setItem(1, 4, new SpreadSheetItem("* B1 D1"));
 
749
    table->setItem(2, 4, new SpreadSheetItem("* B2 D2"));
 
750
    table->setItem(3, 4, new SpreadSheetItem("* B3 D3"));
 
751
    table->setItem(4, 4, new SpreadSheetItem("* B4 D4"));
 
752
    table->setItem(5, 4, new SpreadSheetItem("* B5 D5"));
 
753
    table->setItem(6, 4, new SpreadSheetItem("* B6 D6"));
 
754
    table->setItem(7, 4, new SpreadSheetItem("* B7 D7"));
 
755
    table->setItem(8, 4, new SpreadSheetItem("* B8 D8"));
 
756
    table->setItem(9, 4, new SpreadSheetItem("sum E2 E9"));
 
757
    table->item(9,4)->setBackgroundColor(Qt::lightGray);
 
758
 
 
759
}
 
760
 
 
761
const char *htmlText =
 
762
"<HTML>"
 
763
"<p><b>This demo shows use of <c>QTableWidget</c> with custom handling for"
 
764
" individual cells.</b></p>"
 
765
"<p>Using a customized table item we make it possible to have dynamic"
 
766
" output in different cells. The content that is implemented for this"
 
767
" particular demo is:"
 
768
"<ul>"
 
769
"<li>Addition two cells.</li>"
 
770
"<li>Subtracting one cell from another.</li>"
 
771
"<li>Multiplying two cells.</li>"
 
772
"<li>Dividing one cell with another.</li>"
 
773
"<li>Summing the contents of an arbitrary number of cells.</li>"
 
774
"</HTML>";
 
775
 
 
776
 
 
777
void SpreadSheet::showAbout()
 
778
{
 
779
    QMessageBox::about(this, "About Spread Sheet", htmlText);
 
780
}
 
781
 
 
782
 
 
783
int main(int argc, char** argv) {
 
784
    Q_INIT_RESOURCE(spreadsheet);
 
785
    QApplication app(argc, argv);
 
786
    SpreadSheet sheet(10, 5);
 
787
    sheet.setWindowIcon(QPixmap(":/images/interview.png"));
 
788
    sheet.resize(600, 400);
 
789
    sheet.show();
 
790
    return app.exec();
 
791
}
 
792
 
 
793
#include "main.moc"