Showing posts with label QGraphicsScene. Show all posts
Showing posts with label QGraphicsScene. Show all posts

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

Monday, October 1, 2012

QgraphicsView simple example program


Here is a simple QgraphicsView example program in Qt.

In this example we created a scene (QGraphicsScene) and placed all the items  in this scene by specifying the scene object while creating the graphics item.Andat last we created the view (QGraphicsView) and scene is placed in this view by using setScene() method of QgraphicsView.



#include <QtGui/QApplication>
#include<QGraphicsView>
#include<QGraphicsScene>
#include<QGraphicsSimpleTextItem>
#include<QGraphicsRectItem>
#include<QGraphicsEllipseItem>
#include<QVector>
#include<QGraphicsPolygonItem>

int main( int argc, char **argv )
{
    QApplication app( argc, argv );
    QGraphicsScene scene( QRect( -100, -100, 400, 400 ) );
    scene.setBackgroundBrush(Qt::cyan);


    QGraphicsSimpleTextItem *textItem = new QGraphicsSimpleTextItem(
                "technoyouth10", 0, &scene );
    textItem->setPos( -50, -50 );
    textItem->setFlag(QGraphicsItem::ItemIsMovable);


    QGraphicsRectItem *rectItem = new QGraphicsRectItem(
                QRect( 0, -0, 200, 40 ), 0, &scene );
    rectItem->setPen( QPen( Qt::red, 3, Qt::DashDotLine ) );
    rectItem->setBrush( Qt::green );


    QGraphicsEllipseItem *ellipseItem = new QGraphicsEllipseItem(
                QRect( 80, -80, 100, 75 ),
                0, &scene );
    ellipseItem->setPen( QPen(Qt::yellow) );
    ellipseItem->setBrush( Qt::magenta );


    QVector<QPointF> points;
    points << QPointF( 20, 50 ) << QPointF( 80, 50 ) << QPointF( 110, 80 )
           << QPointF( 50, 130 )<< QPointF( -10, 80 ) ;
    QGraphicsPolygonItem *polygonItem = new QGraphicsPolygonItem(
                QPolygonF( points ), 0, &scene );
    polygonItem->setPen( QPen(Qt::red) );
    polygonItem->setBrush( Qt::yellow );

    QGraphicsView view;
    view.setScene( &scene );
    view.show();
    return app.exec();

}



Output:
Run the program by pressing Ctrl+r...