Thursday, October 4, 2012

QGraphicsView Example Program by inheriting QGraphicsView class


In the prevoius qgraphicsview example we created the view (QgraphicsView) and placed the scene in this view.Now in this example we created a class and inherit this class from QGraphicsView class, so the class being inherited acts like view and we will set the scene for this inherited class.

Check the example program and the output below...
  • graphics.h

#ifndef GRAPHICS_H
#define GRAPHICS_H
#include <QtGui/QWidget>
#include <QGraphicsEllipseItem>
#include <QGraphicsScene>
#include <QGraphicsView>
class graphics : public QGraphicsView
{
    Q_OBJECT
    QGraphicsScene *scene;
    QGraphicsEllipseItem *itm_ellipse;
    QGraphicsTextItem *itm_txt;
    QGraphicsLineItem *itm_line;
    QGraphicsPolygonItem *itm_poly;
    
public:
    graphics(QWidget *parent = 0);
    ~graphics();
};
#endif // GRAPHICS_H

  • graphics.cpp

#include "graphics.h"
graphics::graphics(QWidget *parent)
    : QGraphicsView(parent)
{
    scene = new QGraphicsScene(this);
    scene->setSceneRect( -300,-300,600,600 );
this->setScene(scene); itm_ellipse = new QGraphicsEllipseItem(0,scene ); itm_ellipse->setRect( -100.0, -100.0, 100.0, 100.0 ); itm_ellipse->setFlag(QGraphicsItem::ItemIsMovable);

    itm_txt = new QGraphicsTextItem("hello",0,scene);
    itm_txt->setPos(100,100);

    itm_line = new QGraphicsLineItem(0,0,100,100,0,scene);

    itm_poly = new QGraphicsPolygonItem(0,scene);
    QPolygonF poly;
    poly<<QPoint(100,100)<<QPoint(200,100)<<QPoint(200,200)<<QPoint(100,200);
    itm_poly->setPolygon(poly);
}

graphics::~graphics()
{
    
}
  • main.cpp

#include <QtGui/QApplication>
#include "graphics.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    graphics w;
    w.show();
    
    return a.exec();
}


Output:


No comments:

Post a Comment