PDA

View Full Version : Automatic deselecting of QGraphicsItems after clicking somewhere on screen



zdenicka01
28th March 2010, 19:08
Hello,

I'd like to do a program, which allows user to "arrange" nodes (QGraphicsObjects) on screen (QGraphicsScene / QGraphicsView). Of course this is very simplified description.

Important part of "arranging" is selecting existing nodes by clicking on it. I decided to use QGraphicsItem::setSelected() method. But selected nodes are somehow automatically deselected (and redrawed) after clicking somewhere on screen.

I thought all logic of seleting/deselecting must be added by programmer, because I read documentation for these functions and can't see anythink about it. But maybe I overlooked something?

Thanks

------

Here is (again simplified) code I'm using, just with one added node by default. Probably most interesting line is 53, where I select the clicked node:



#include <QtGui>
#include <QtGui/QGraphicsView>
#include <QMouseEvent>
#include <QRectF>
#include <QPainterPath>
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <QWidget>
#include <QColor>
#include <QGraphicsScene>
#include <QGraphicsObject>
#include <QGraphicsSceneMouseEvent>

class Node : public QGraphicsObject
{
public:
Node() { setFlag(ItemIsSelectable); }

QRectF boundingRect() const
{
qreal adjust = 2;
return QRectF(-10 - adjust, -10 - adjust, 23 + adjust, 23 + adjust);
}

QPainterPath shape() const
{
QPainterPath path;
path.addEllipse(-10, -10, 20, 20);
return path;
}

void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget )
{
QColor fill, stroke;

if( this->isSelected() ) {
fill = Qt::yellow;
stroke = Qt::gray;
}
else {
fill = Qt::green;
stroke = Qt::black;
}

painter->setBrush(fill);
painter->setPen(QPen( stroke, 0));
painter->drawEllipse(-10, -10, 20, 20);
}

protected:
void mouseReleaseEvent( QGraphicsSceneMouseEvent *event )
{
this->setSelected( !this->isSelected() );
this->update( this->boundingRect() );
event->accept();
}

void mousePressEvent( QGraphicsSceneMouseEvent *event )
{
}
};

class Playground : public QGraphicsView
{
public:
Playground()
{
QGraphicsScene * scene = new QGraphicsScene( this );
scene->setItemIndexMethod(QGraphicsScene::NoIndex);
scene->setSceneRect(0, 0, 200, 200);
this->setScene(scene);

Node *newNode = new Node();
scene->addItem( newNode );
newNode->setPos( 100, 100 );
}

protected:

void drawBackground( QPainter *painter, const QRectF &rect )
{
setInteractive ( true );
QRectF sceneRect = this->sceneRect();
painter->fillRect(rect.intersect(sceneRect), Qt::gray);
painter->setBrush(Qt::NoBrush);
painter->drawRect(sceneRect);
}
};


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

Playground playground;
playground.show();

return app.exec();
}