Tuesday, August 2, 2011

Save Screenshot of QGraphicsScene

In order to display items that are residing in QGraphicsScene, QGraphicsView is used. In the sample application Custom QDialog contains a QGraphicsView with a QGraphicsScene inside it.

Project Directory Structure in Qt Creator IDE :



SaveQGraphicsSceneAsImage.pro is the project configuration file and contains:
QT       += core gui
TARGET = SaveQGraphicsSceneAsImage
TEMPLATE = app
SOURCES += main.cpp\
        Dialog.cpp
HEADERS  += Dialog.h


main.cpp file contains the custom QDialog instance and shows it.
#include <QApplication>
#include "Dialog.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();
    return a.exec();
}


Dialog.h file contains custom QDialog interface.
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
class QGraphicsScene;
class QGraphicsView;
class QVBoxLayout;

class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = 0);
    ~Dialog();

public slots:
    void sl_saveSceneAsImage();

private:
    QGraphicsScene* scene;
    QGraphicsView* view;
    QVBoxLayout* layout;
    QPushButton* btnSaveScene;
};
#endif // DIALOG_H


Dialog.cpp file contains implementation details for the custom QDialog.
#include "Dialog.h"

#include <QGraphicsView>
#include <QGraphicsScene>
#include <QVBoxLayout>
#include <QPushButton>
#include <QString>
#include <QFileDialog>
#include <QPixmap>

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
{
    scene = new QGraphicsScene(this);
    scene->addEllipse(22,3,12,13,QPen(QColor("red")));
    scene->addLine(1,2,8,9,QPen("blue"));
    scene->addRect(12,12,6,7,QPen("green"));
    view = new QGraphicsView(scene,this);
    layout = new QVBoxLayout(this);
    btnSaveScene = new QPushButton("Take Scene SnapShot");
    connect(btnSaveScene, SIGNAL(clicked()), this, SLOT(sl_saveSceneAsImage()));
    layout->addWidget(view);
    layout->addWidget(btnSaveScene);
    setLayout(layout);
    resize(270,200);
}

Dialog::~Dialog()
{
    delete btnSaveScene;
    delete scene;
    delete view;
    delete layout;
}

void Dialog::sl_saveSceneAsImage()
{
    QString fileName = QFileDialog::getSaveFileName(this, "Save Scene", "", "Image (*.png)");
    QPixmap pixMap = QPixmap::grabWidget(view);
    pixMap.save(fileName);
    close();
}


QGraphicsScene content can be saved as a png image file. Sample QGraphicsScene contains items of type line,rectangle and ellipse. Taken snapshot displays all these items inside of saved snapshot.

sl_saveSceneAsImage() slot of custom QDialog uses Qpixmap::grabWidget function to create a pixmap and paints the QGraphicsView inside it. Because all the child items are also painted in then QGraphicsScene becomes painted inside snapshot, too.

As a result Qpixmap instance is saved to specified location with :
pixMap.save(fileName);


Sample QGraphicsScene content :




Saved QGraphicsScene Snapshot :



No comments:

Post a Comment