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...


2 comments: