forked from sqlitebrowser/sqlitebrowser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlotDock.cpp
More file actions
530 lines (470 loc) · 20.6 KB
/
PlotDock.cpp
File metadata and controls
530 lines (470 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
#include "PlotDock.h"
#include "ui_PlotDock.h"
#include "Settings.h"
#include "sqlitetablemodel.h"
#include "FileDialog.h"
#include "MainWindow.h" // Just for BrowseDataTableSettings, not for the actual main window class
PlotDock::PlotDock(QWidget* parent)
: QDialog(parent),
ui(new Ui::PlotDock),
m_currentPlotModel(nullptr),
m_currentTableSettings(nullptr)
{
ui->setupUi(this);
// Init widgets
ui->treePlotColumns->setSelectionMode(QAbstractItemView::NoSelection);
// Restore state
ui->splitterForPlot->restoreState(Settings::getSettingsValue("PlotDock", "splitterSize").toByteArray());
ui->comboLineType->setCurrentIndex(Settings::getSettingsValue("PlotDock", "lineType").toInt());
ui->comboPointShape->setCurrentIndex(Settings::getSettingsValue("PlotDock", "pointShape").toInt());
}
PlotDock::~PlotDock()
{
// Save state
Settings::setSettingsValue("PlotDock", "splitterSize", ui->splitterForPlot->saveState());
Settings::setSettingsValue("PlotDock", "lineType", ui->comboLineType->currentIndex());
Settings::setSettingsValue("PlotDock", "pointShape", ui->comboPointShape->currentIndex());
// Finally, delete all widgets
delete ui;
}
void PlotDock::updatePlot(SqliteTableModel* model, BrowseDataTableSettings* settings, bool update, bool keepOrResetSelection)
{
// add columns to x/y selection tree widget
if(update)
{
// Store pointer to the current browse table settings in the main window
m_currentTableSettings = settings;
// disconnect treeplotcolumns item changed updates
disconnect(ui->treePlotColumns, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this,SLOT(on_treePlotColumns_itemChanged(QTreeWidgetItem*,int)));
m_currentPlotModel = model;
// save current selected columns, so we can restore them after the update
QString sItemX; // selected X column
QMap<QString, QColor> mapItemsY; // selected Y columns with color
if(keepOrResetSelection)
{
// Store the currently selected plot columns to restore them later
for(int i = 0; i < ui->treePlotColumns->topLevelItemCount(); ++i)
{
QTreeWidgetItem* item = ui->treePlotColumns->topLevelItem(i);
if(item->checkState(PlotColumnX) == Qt::Checked)
sItemX = item->text(PlotColumnField);
if(item->checkState(PlotColumnY) == Qt::Checked)
mapItemsY[item->text(PlotColumnField)] = item->backgroundColor(PlotColumnY);
}
} else {
// Get the plot columns to select from the stored browse table information
sItemX = m_currentTableSettings->plotXAxis;
QMap<QString, PlotSettings> axesY = m_currentTableSettings->plotYAxes;
auto it = axesY.constBegin();
while(it != axesY.constEnd())
{
mapItemsY.insert(it.key(), it.value().colour);
++it;
}
}
ui->treePlotColumns->clear();
if(model)
{
// Add each column with a supported data type to the column selection view
for(int i=0;i<model->columnCount();++i)
{
QVariant::Type columntype = guessDataType(model, i);
if(columntype != QVariant::String && columntype != QVariant::Invalid)
{
QTreeWidgetItem* columnitem = new QTreeWidgetItem(ui->treePlotColumns);
// maybe i make this more complicated than i should
// but store the model column index in the first 16 bit and the type
// in the other 16 bits
uint itemdata = 0;
itemdata = i << 16;
itemdata |= columntype;
columnitem->setData(PlotColumnField, Qt::UserRole, itemdata);
columnitem->setText(PlotColumnField, model->headerData(i, Qt::Horizontal).toString());
// restore previous check state
if(mapItemsY.contains(columnitem->text(PlotColumnField)))
{
columnitem->setCheckState(PlotColumnY, Qt::Checked);
columnitem->setBackgroundColor(PlotColumnY, mapItemsY[columnitem->text(PlotColumnField)]);
}
else
columnitem->setCheckState(PlotColumnY, Qt::Unchecked);
if(sItemX == columnitem->text(PlotColumnField))
columnitem->setCheckState(PlotColumnX, Qt::Checked);
else
columnitem->setCheckState(PlotColumnX, Qt::Unchecked);
}
}
// Add a row number column at the beginning of the column list, but only when there were (other) columns added
if(ui->treePlotColumns->topLevelItemCount())
{
QTreeWidgetItem* columnitem = new QTreeWidgetItem(ui->treePlotColumns);
// Just set all bits in the user role information field here to somehow indicate what column this is
uint itemdata = -1;
columnitem->setData(PlotColumnField, Qt::UserRole, itemdata);
columnitem->setText(PlotColumnField, tr("Row #"));
// restore previous check state
if(mapItemsY.contains(columnitem->text(PlotColumnField)))
{
columnitem->setCheckState(PlotColumnY, Qt::Checked);
columnitem->setBackgroundColor(PlotColumnY, mapItemsY[columnitem->text(PlotColumnField)]);
} else {
columnitem->setCheckState(PlotColumnY, Qt::Unchecked);
}
if(sItemX == columnitem->text(PlotColumnField))
columnitem->setCheckState(PlotColumnX, Qt::Checked);
else
columnitem->setCheckState(PlotColumnX, Qt::Unchecked);
ui->treePlotColumns->takeTopLevelItem(ui->treePlotColumns->indexOfTopLevelItem(columnitem));
ui->treePlotColumns->insertTopLevelItem(0, columnitem);
}
}
ui->plotWidget->yAxis->setLabel("Y");
ui->plotWidget->xAxis->setLabel("X");
connect(ui->treePlotColumns, &QTreeWidget::itemChanged, this, &PlotDock::on_treePlotColumns_itemChanged);
}
// search for the x axis select
QTreeWidgetItem* xitem = 0;
for(int i = 0; i < ui->treePlotColumns->topLevelItemCount(); ++i)
{
xitem = ui->treePlotColumns->topLevelItem(i);
if(xitem->checkState(PlotColumnX) == Qt::Checked)
break;
xitem = 0;
}
QStringList yAxisLabels;
ui->plotWidget->clearGraphs();
if(xitem)
{
// regain the model column index and the datatype
// leading 16 bit are column index, the other 16 bit are the datatype
// right now datatype is only important for X axis (date, non date)
uint xitemdata = xitem->data(PlotColumnField, Qt::UserRole).toUInt();
int x = xitemdata >> 16;
int xtype = xitemdata & (uint)0xFF;
// check if we have a x axis with datetime data
if(xtype == QVariant::DateTime)
{
ui->plotWidget->xAxis->setTickLabelType(QCPAxis::ltDateTime);
ui->plotWidget->xAxis->setDateTimeFormat("yyyy-MM-dd");
} else {
ui->plotWidget->xAxis->setTickLabelType(QCPAxis::ltNumber);
}
// add graph for each selected y axis
for(int i = 0; i < ui->treePlotColumns->topLevelItemCount(); ++i)
{
QTreeWidgetItem* item = ui->treePlotColumns->topLevelItem(i);
if(item->checkState((PlotColumnY)) == Qt::Checked)
{
// regain the model column index and the datatype
// leading 16 bit are column index
uint itemdata = item->data(0, Qt::UserRole).toUInt();
int column = itemdata >> 16;
QCPGraph* graph = ui->plotWidget->addGraph();
graph->setPen(QPen(item->backgroundColor(PlotColumnY)));
// prepare the data vectors for qcustomplot
// possible improvement might be a QVector subclass that directly
// access the model data, to save memory, we are copying here
QVector<double> xdata(model->rowCount()), ydata(model->rowCount());
for(int i = 0; i < model->rowCount(); ++i)
{
// convert x type axis if it's datetime
if(xtype == QVariant::DateTime)
{
QString s = model->data(model->index(i, x)).toString();
QDateTime d = QDateTime::fromString(s, Qt::ISODate);
xdata[i] = d.toMSecsSinceEpoch() / 1000.0;
} else {
// Get the x value for this point. If the selected column is -1, i.e. the row number, just use the current row number from the loop
// instead of retrieving some value from the model.
if(x == 0xFFFF)
xdata[i] = i+1;
else
xdata[i] = model->data(model->index(i, x)).toDouble();
}
// Get the y value for this point. If the selected column is -1, i.e. the row number, just use the current row number from the loop
// instead of retrieving some value from the model.
QVariant pointdata;
if(column == 0xFFFF)
pointdata = i+1;
else
pointdata = model->data(model->index(i, column), Qt::EditRole);
if(pointdata.isNull())
ydata[i] = qQNaN();
else
ydata[i] = pointdata.toDouble();
}
// set some graph styles
graph->setData(xdata, ydata);
graph->setLineStyle((QCPGraph::LineStyle) ui->comboLineType->currentIndex());
// WARN: ssDot is removed
int shapeIdx = ui->comboPointShape->currentIndex();
if (shapeIdx > 0) shapeIdx += 1;
graph->setScatterStyle(QCPScatterStyle((QCPScatterStyle::ScatterShape)shapeIdx, 5));
// gather Y label column names
yAxisLabels << model->headerData(column, Qt::Horizontal).toString();
}
}
ui->plotWidget->rescaleAxes(true);
// set axis labels
ui->plotWidget->xAxis->setLabel(model->headerData(x, Qt::Horizontal).toString());
ui->plotWidget->yAxis->setLabel(yAxisLabels.join("|"));
}
ui->plotWidget->replot();
}
void PlotDock::on_treePlotColumns_itemChanged(QTreeWidgetItem* changeitem, int column)
{
// disable change updates, or we get unwanted redrawing and weird behavior
disconnect(ui->treePlotColumns, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this,SLOT(on_treePlotColumns_itemChanged(QTreeWidgetItem*,int)));
// make sure only 1 X axis is selected
if(column == PlotColumnX)
{
for(int i = 0; i < ui->treePlotColumns->topLevelItemCount(); ++i)
{
QTreeWidgetItem* item = ui->treePlotColumns->topLevelItem(i);
if(item->checkState(column) == Qt::Checked && item != changeitem)
{
item->setCheckState(column, Qt::Unchecked);
}
}
// Save settings for this table
if(m_currentTableSettings)
{
if(changeitem->checkState(column) == Qt::Checked)
m_currentTableSettings->plotXAxis = changeitem->text(PlotColumnField);
else
m_currentTableSettings->plotXAxis = QString();
}
} else if(column == PlotColumnY) {
if(changeitem->checkState(column) == Qt::Checked)
{
// Generate a default colour if none isn't set yet
QColor colour = changeitem->backgroundColor(column);
if(!colour.isValid())
{
static int last_colour_index = 0;
switch(last_colour_index++)
{
case 0:
colour = QColor(0, 69, 134);
break;
case 1:
colour = QColor(255, 66, 14);
break;
case 2:
colour = QColor(255, 211, 32);
break;
case 3:
colour = QColor(87, 157, 28);
break;
case 4:
colour = QColor(126, 0, 33);
break;
case 5:
colour = QColor(131, 202, 255);
break;
case 6:
colour = QColor(49, 64, 4);
break;
case 7:
colour = QColor(174, 207, 0);
break;
case 8:
colour = QColor(75, 31, 111);
break;
case 9:
colour = QColor(255, 149, 14);
break;
case 10:
colour = QColor(197, 00, 11);
break;
case 11:
colour = QColor(0, 132, 209);
// Since this is the last colour in our table, reset the counter back
// to the first colour
last_colour_index = 0;
break;
default:
// NOTE: This shouldn't happen!
colour = QColor(0, 0, 0);
break;
}
}
// Set colour
changeitem->setBackgroundColor(column, colour);
// Save settings for this table
if(m_currentTableSettings)
{
PlotSettings& plot_settings = m_currentTableSettings->plotYAxes[changeitem->text(PlotColumnField)];
plot_settings.colour = colour;
plot_settings.lineStyle = ui->comboLineType->currentIndex();
plot_settings.pointShape = (ui->comboPointShape->currentIndex() > 0 ? (ui->comboPointShape->currentIndex()+1) : ui->comboPointShape->currentIndex());
}
}
}
connect(ui->treePlotColumns, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this,SLOT(on_treePlotColumns_itemChanged(QTreeWidgetItem*,int)));
updatePlot(m_currentPlotModel, m_currentTableSettings, false);
}
void PlotDock::on_treePlotColumns_itemDoubleClicked(QTreeWidgetItem* item, int column)
{
// disable change updates, or we get unwanted redrawing and weird behavior
disconnect(ui->treePlotColumns, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this,SLOT(on_treePlotColumns_itemChanged(QTreeWidgetItem*,int)));
if(column == PlotColumnY)
{
// On double click open the colordialog
QColorDialog colordialog(this);
QColor curbkcolor = item->backgroundColor(column);
QColor precolor = !curbkcolor.isValid() ? (Qt::GlobalColor)(qrand() % 13 + 5) : curbkcolor;
QColor color = colordialog.getColor(precolor, this, tr("Choose a axis color"));
if(color.isValid())
{
item->setCheckState(column, Qt::Checked);
item->setBackgroundColor(column, color);
// Save settings for this table
if(m_currentTableSettings)
{
PlotSettings& plot_settings = m_currentTableSettings->plotYAxes[item->text(PlotColumnField)];
plot_settings.colour = color;
plot_settings.lineStyle = ui->comboLineType->currentIndex();
plot_settings.pointShape = (ui->comboPointShape->currentIndex() > 0 ? (ui->comboPointShape->currentIndex()+1) : ui->comboPointShape->currentIndex());
}
} else {
item->setCheckState(column, Qt::Unchecked);
// Save settings for this table
if(m_currentTableSettings)
m_currentTableSettings->plotYAxes.remove(item->text(PlotColumnField));
}
}
connect(ui->treePlotColumns, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this,SLOT(on_treePlotColumns_itemChanged(QTreeWidgetItem*,int)));
updatePlot(m_currentPlotModel, m_currentTableSettings, false);
}
void PlotDock::on_butSavePlot_clicked()
{
QString fileName = FileDialog::getSaveFileName(this,
tr("Choose a filename to save under"),
tr("PNG(*.png);;JPG(*.jpg);;PDF(*.pdf);;BMP(*.bmp);;All Files(*)")
);
if(!fileName.isEmpty())
{
if(fileName.endsWith(".png", Qt::CaseInsensitive))
{
ui->plotWidget->savePng(fileName);
}
else if(fileName.endsWith(".jpg", Qt::CaseInsensitive))
{
ui->plotWidget->saveJpg(fileName);
}
else if(fileName.endsWith(".pdf", Qt::CaseInsensitive))
{
ui->plotWidget->savePdf(fileName);
}
else if(fileName.endsWith(".bmp", Qt::CaseInsensitive))
{
ui->plotWidget->saveBmp(fileName);
}
else
{
fileName += ".png";
ui->plotWidget->savePng(fileName);
}
}
}
void PlotDock::on_comboLineType_currentIndexChanged(int index)
{
Q_ASSERT(index >= QCPGraph::lsNone &&
index <= QCPGraph::lsImpulse);
QCPGraph::LineStyle lineStyle = (QCPGraph::LineStyle) index;
for (int i = 0, ie = ui->plotWidget->graphCount(); i < ie; ++i)
{
QCPGraph * graph = ui->plotWidget->graph(i);
if (graph)
graph->setLineStyle(lineStyle);
}
ui->plotWidget->replot();
// Save settings for this table
if(m_currentTableSettings)
{
QMap<QString, PlotSettings>& graphs = m_currentTableSettings->plotYAxes;
auto it = graphs.begin();
while(it != graphs.end())
{
it.value().lineStyle = lineStyle;
++it;
}
}
}
void PlotDock::on_comboPointShape_currentIndexChanged(int index)
{
// WARN: because ssDot point shape is removed
if (index > 0) index += 1;
Q_ASSERT(index >= QCPScatterStyle::ssNone &&
index < QCPScatterStyle::ssPixmap);
QCPScatterStyle::ScatterShape shape = (QCPScatterStyle::ScatterShape) index;
for (int i = 0, ie = ui->plotWidget->graphCount(); i < ie; ++i)
{
QCPGraph * graph = ui->plotWidget->graph(i);
if (graph)
graph->setScatterStyle(QCPScatterStyle(shape, 5));
}
ui->plotWidget->replot();
// Save settings for this table
if(m_currentTableSettings)
{
QMap<QString, PlotSettings>& graphs = m_currentTableSettings->plotYAxes;
auto it = graphs.begin();
while(it != graphs.end())
{
it.value().pointShape = shape;
++it;
}
}
}
QVariant::Type PlotDock::guessDataType(SqliteTableModel* model, int column)
{
QVariant::Type type = QVariant::Invalid;
for(int i = 0; i < std::min(10, model->rowCount()) && type != QVariant::String; ++i)
{
QVariant data = model->data(model->index(i, column), Qt::EditRole);
if(data.isNull() || data.convert(QVariant::Double))
{
type = QVariant::Double;
} else {
QString s = model->data(model->index(i, column)).toString();
QDate d = QDate::fromString(s, Qt::ISODate);
if(d.isValid())
type = QVariant::DateTime;
else
type = QVariant::String;
}
}
return type;
}
void PlotDock::fetchAllData()
{
if(m_currentPlotModel)
{
// Show progress dialog because fetching all data might take some time
QProgressDialog progress(tr("Fetching all data..."),
tr("Cancel"), m_currentPlotModel->rowCount(), m_currentPlotModel->totalRowCount());
progress.setWindowModality(Qt::ApplicationModal);
progress.show();
qApp->processEvents();
// Make sure all data is loaded
while(m_currentPlotModel->canFetchMore())
{
// Fetch the next bunch of data
m_currentPlotModel->fetchMore();
// Update the progress dialog and stop loading data when the cancel button was pressed
progress.setValue(m_currentPlotModel->rowCount());
qApp->processEvents();
if(progress.wasCanceled())
break;
}
// Update plot
updatePlot(m_currentPlotModel, m_currentTableSettings);
}
}