diff --git a/src/PlotDock.cpp b/src/PlotDock.cpp index 36ff9957..bbfd7eea 100644 --- a/src/PlotDock.cpp +++ b/src/PlotDock.cpp @@ -5,6 +5,9 @@ #include "FileDialog.h" #include "MainWindow.h" // Just for BrowseDataTableSettings, not for the actual main window class +#include +#include + PlotDock::PlotDock(QWidget* parent) : QDialog(parent), ui(new Ui::PlotDock), @@ -40,18 +43,28 @@ PlotDock::PlotDock(QWidget* parent) QShortcut* shortcutCopy = new QShortcut(QKeySequence::Copy, ui->plotWidget, nullptr, nullptr, Qt::WidgetShortcut); connect(shortcutCopy, SIGNAL(activated()), this, SLOT(copy())); + QShortcut* shortcutPrint = new QShortcut(QKeySequence::Print, ui->plotWidget, nullptr, nullptr, Qt::WidgetShortcut); + connect(shortcutPrint, &QShortcut::activated, this, &PlotDock::openPrintDialog); + ui->plotWidget->setContextMenuPolicy(Qt::CustomContextMenu); // Set up context menu m_contextMenu = new QMenu(this); + QAction* copyAction = new QAction(QIcon(":/icons/copy"), tr("Copy"), m_contextMenu); copyAction->setShortcut(shortcutCopy->key()); m_contextMenu->addAction(copyAction); - connect(copyAction, &QAction::triggered, [&]() { copy(); }); + QAction* printAction = new QAction(QIcon(":/icons/print"), tr("Print..."), m_contextMenu); + printAction->setShortcut(shortcutPrint->key()); + m_contextMenu->addAction(printAction); + connect(printAction, &QAction::triggered, [&]() { + openPrintDialog(); + }); + QAction* showLegendAction = new QAction(tr("Show legend"), m_contextMenu); showLegendAction->setCheckable(true); m_contextMenu->addAction(showLegendAction); @@ -851,3 +864,27 @@ void PlotDock::reject() // dock go away return; } + +void PlotDock::openPrintDialog() +{ + QPrinter printer; + QPrintPreviewDialog previewDialog(&printer, this); + connect(&previewDialog, &QPrintPreviewDialog::paintRequested, this, &PlotDock::renderPlot); + previewDialog.exec(); +} + +void PlotDock::renderPlot(QPrinter* printer) +{ + QCPPainter painter(printer); + QRectF pageRect = printer->pageRect(QPrinter::DevicePixel); + + int plotWidth = ui->plotWidget->viewport().width(); + int plotHeight = ui->plotWidget->viewport().height(); + double scale = pageRect.width()/(double)plotWidth; + + painter.setMode(QCPPainter::pmVectorized); + painter.setMode(QCPPainter::pmNoCaching); + + painter.scale(scale, scale); + ui->plotWidget->toPainter(&painter, plotWidth, plotHeight); +} diff --git a/src/PlotDock.h b/src/PlotDock.h index fb609f9a..aeeb9c00 100644 --- a/src/PlotDock.h +++ b/src/PlotDock.h @@ -7,6 +7,7 @@ class SqliteTableModel; class QTreeWidgetItem; +class QPrinter; struct BrowseDataTableSettings; namespace Ui { @@ -110,6 +111,8 @@ private slots: void copy(); void toggleLegendVisible(bool visible); void toggleStackedBars(bool stacked); + void openPrintDialog(); + void renderPlot(QPrinter* printer); }; #endif