PDA

View Full Version : Multiple use of QGraphicScene



Xtresis
6th September 2010, 10:54
Hi all,

I'm quite new here and just started with Qt for a couple of days. Currently I'm working on my first project with Qt and I'm trying to draw some kind of map where a few red dots will become visible after putting data in a table.

I've already created a ui in Qt with a QGraphicsView included. Then created a QGraphicsScene named 'scene'. In that scene i draw a few circles and lines with the following code:



//draw map
void Unknown::drawMap(int width)
{
QGraphicsScene *scene = new QGraphicsScene;
scene->setSceneRect(0, 0, width, width);
scene->setBackgroundBrush(Qt::white);

//draw horizontal & vertical line
scene->addLine(0, (width/2), width, (width/2));
scene->addLine((width/2), 0, (width/2), width);

//draw 5 circles
int x = (width/12), y = width-(width/6);
for(int i=0; i<5; i++)
{
scene->addEllipse(x, x, y, y, QColor(180, 180, 180), Qt::NoBrush);
x = x + (width/12);
y = y - (width/6);
}

//put scene on screen

ui->graphicsView->setScene(scene);

This works like a charm. However, when this function is finished I would like to add some red dots to this QGraphicsScene with a different function.


//draw dot
void Unknown::drawDot()
{
scene->addEllipse(50, 50, 1, 1, QColor(255, 0, 0), Qt::NoBrush);
ui->graphicsView->setScene(scene);
}

When applying this function to the main program and build it, I get the error: "scene not declared". I do understand why, but I don't know how to solve this problem without getting errors. I already tried the following in the main program:


#include "unknown.h"
#include "ui_unknown.h"

QGraphicsScene *scene = new QGraphicsScene;

When adding this to the program, the building process completes succesfully. The program shuts down immediately though.

Can someone help me out here?

wysota
6th September 2010, 11:18
The scene variable in yourd drawMap() is local to the method. Make it a member of your class and everything will be fine. This is a lack-of-C++-skills problem, you know...

Xtresis
6th September 2010, 11:35
Thanks for you reply. I know indeed that this is a lack-of-C++-skills, but I can't figure out how to fix this problem ( and that's why I put this in the Newbie subforum ). I would really appriciate an example how to solve this is the right way.

Thank you!

nish
6th September 2010, 11:46
if you dont want to make it a member than you can access the scene by calling


//draw dot
void Unknown::drawDot()
{
//scene->addEllipse(50, 50, 1, 1, QColor(255, 0, 0), Qt::NoBrush);
ui->graphicsView->scene()->addEllipse(50, 50, 1, 1, QColor(255, 0, 0), Qt::NoBrush);
//We already set this in previous function so no need now
//ui->graphicsView->setScene(scene);
}

but as suggested you should learn to make a class.

Xtresis
6th September 2010, 12:06
Thank you for your reply. Your solution works indeed, but I will try it with a class as well. Already found someone in my study book, so I think that shouldn't be a problem.