Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Print a graph



  • I found this code on internet:
    https://www.qcustomplot.com/index.php/support/forum/976

    it works but I want to paint only the graph without the side dish for the printer..on a dockwidget..so I tried to write:
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QPrintDialog>

    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    mPlot(new QCustomPlot(this))
    {
    ui->setupUi(this);

    setCentralWidget(mPlot);

    // just setting up a plot, nothing special happening here:
    mPlot->axisRect()->setupFullAxesBox(true);
    mPlot->addGraph()->addData(QVector<double>() << 1 << 2 << 3 << 4, QVector<double>() << 1 << 2 << 4 << 8);
    mPlot->rescaleAxes();
    mPlot->legend->setVisible(true);
    mPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignLeft|Qt::AlignTop); // align legend to top left corner

    ui->menuBar->addAction("Print Preview", this, SLOT(printPreview()));
    }

    MainWindow::~MainWindow()
    {
    delete ui;
    }

    void MainWindow::printPreview()
    {
    QDockWidget dock;
    // QPrinter printer;
    //QPrintPreviewDialog previewDialog(&dock, this);
    //dock.setFloating(true);
    //dock.show();
    //dock.setFloating(true);
    connect(&dock, SIGNAL(paintRequested(QDockWidget*)), SLOT(renderPlot(QDockWidget*)));

    dock.show();
    }

    void MainWindow::renderPlot(QDockWidget * dock)
    {
    //printer->setPageSize(QPrinter::A4);
    QCPPainter painter(dock);
    //dock->setFloating(true);
    //QRectF pageRect = printer->pageRect(QPrinter::DevicePixel);

    int plotWidth = mPlot->viewport().width();
    int plotHeight = mPlot->viewport().height();
    // double scale = pageRect.width()/(double)plotWidth;

    painter.setMode(QCPPainter::pmVectorized);
    painter.setMode(QCPPainter::pmNoCaching);
    painter.setMode(QCPPainter::pmNonCosmetic); // comment this out if you want cosmetic thin lines (always 1 pixel thick independent of pdf zoom level)

    //painter.scale(scale, scale);
    mPlot->toPainter(&painter, plotWidth, plotHeight);
    dock->show();
    //dock->setFloating(true);
    }

    but It doesn't work..I want only to have a copy of the graph in a dockwidget and not the side dish gray


Log in to reply