Reputation: 942
My objective:
I want to draw a simple rectangle of length and breadth 100, at position x = 0, y = 0 on QGraphicsView. That should look something like this
What i have done so far I have created a object (on heap) called block_realiser in constructor of homepage(MainWindow), it accepts QGraphicsView as parameter in constructor. I created a QGraphicsScene (on heap) in block realiser constructor, and in its constructor itself I set this scene to the view. There is a function called drawRect in block_realiser that is supposed to draw a rect of 100x100 at (0,0). Code is
Block_Realiser::Block_Realiser(QGraphicsView *view, QObject *parent) :
QObject(parent)
{
m_View = view;
m_Scene = new QGraphicsScene;
m_View->setScene(m_Scene);
}
void Block_Realiser::drawRect()
{
m_Scene->addRect(m_View->x(), m_View->y(),
100, 100);
}
Now coming to my problem. There are two ways of calling the function drawRect in constructor of homepage. One is through timer (after 100 ms delay) and another is to call directly 1) Through timer, code is
HomePage::HomePage(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::HomePage)
{
ui->setupUi(this);
realiser = new Block_Realiser(ui->graphicsView);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), realiser, SLOT(drawRect()));
connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater()));
timer->setSingleShot(true);
timer->start(100);
}
Output is
2) Calling function directly
Code is
HomePage::HomePage(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::HomePage)
{
ui->setupUi(this);
realiser = new Block_Realiser(ui->graphicsView);
realiser->drawRect();
}
So can anyone explain me what is going on in the above two cases? And how I can achieve my objective?. I have previously subclassed qwidget and reimplemented its paintEvent to achieve the same result of my objective. But this is not happening in qgraphicsscene. Please help me out. If any details missing, let me know.
Upvotes: 0
Views: 232
Reputation: 12931
The views position is recalculated when its shown. When you use the timer, the m_View->x()
and m_View->y()
values are probably different than when you call your drawRect
method directly. This would mean different width and height values. I don't understand why do you use the views position + 100 to calculate the size of your rect.
If you want your rect to be in the upper left corner, just set the alignment to your view:
m_View->setAlignment(Qt::AlignLeft | Qt::AlignTop);
Upvotes: 1
Reputation: 2886
AddRect coordinates are relative to the item, not to the widget containing the qgraphicscene.
You should call
m_Scene->addRect(0,0,100,100);
Upvotes: 1