PDA

View Full Version : My first program with QGraphicsView



Morea
8th September 2006, 18:10
I think I store all my questions about QGraphicsView in this thread.

First problem, I have a class Planet that is subclassedfrom GraphicsItem and I have this to draw it


void Planet::paint(QPainter* painter, QStyleOptionGraphicsItem* option,QWidget* widget)
{
painter->setBrush(QColor(Qt::red));
painter->drawEllipse(x,y,2*radius,2*radius);
}

but all I get is a black circle on a white background. And the view isn't updated very much. How do I draw the ellipse and how do I update it more often?

jpn
8th September 2006, 18:19
There is QGraphicsEllipseItem (http://doc.trolltech.com/4.2/qgraphicsellipseitem.html) which provides an GV ellipse item out of the box.
You may then use QAbstractGraphicsShapeItem::setBrush() (http://doc.trolltech.com/4.2/qabstractgraphicsshapeitem.html#setBrush) and QAbstractGraphicsShapeItem::setPen() (http://doc.trolltech.com/4.2/qabstractgraphicsshapeitem.html#setPen) to set brush and pen, respectively.

Morea
8th September 2006, 18:35
There is QGraphicsEllipseItem (http://doc.trolltech.com/4.2/qgraphicsellipseitem.html) which provides an GV ellipse item out of the box.
You may then use QAbstractGraphicsShapeItem::setBrush() (http://doc.trolltech.com/4.2/qabstractgraphicsshapeitem.html#setBrush) and QAbstractGraphicsShapeItem::setPen() (http://doc.trolltech.com/4.2/qabstractgraphicsshapeitem.html#setPen) to set brush and pen, respectively.

So I tried:



Planet::Planet()
{
radius = 31;
x=rand()%500;
y=rand()%500;
setRect(x,y,2*radius,2*radius);
brush =QBrush(QColor(45,221,182));
pen = QPen(QColor(200,100,100));
}

void Planet::paint(QPainter* painter, QStyleOptionGraphicsItem* option,QWidget* widget)
{
setBrush(brush);
setPen(pen);
painter->drawEllipse(x,y,2*radius,2*radius);
}


but with the same result.

jpn
8th September 2006, 19:11
I meant that for an ellipse you don't need to implement your own QGraphicsItem, you can simply use a QGrapgicsEllipseItem instead:


#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>

int main( int argc, char **argv )
{
QApplication app(argc, argv);

QGraphicsScene scene(QRectF(0,0,100,100));
scene.addEllipse(QRectF(25,40,50,20), QPen(Qt::green), QBrush(Qt::red));
QGraphicsView view(&scene);
view.show();

return app.exec();
}

Morea
8th September 2006, 19:46
With this constructor



Planet::Planet() //:QGraphicsEllipseItem(QRect(0,0,0,0))
{
setBrush(QBrush(QColor(45,21,182)));
setPen(QPen(QColor(200,10,10)));
}

I get different colors, but it doesn't change the Brush if I add


setBrush(QBrush(QColor(rand()%255,rand()%255,rand( )%255)));


to the

void Planet::paint(QPainter* painter, QStyleOptionGraphicsItem* option,QWidget* widget)

function.
Strange.