PDA

View Full Version : I have a class with Qtimer, if I dont create it as new it does not works...



tonnot
1st March 2011, 13:31
I dont know very well what is happen....

I have a class with some utilities, one of them is a cronometer.


W_qtutil *w_qt=new W_qtutil();
w_qt->time_start_crono(ui->my_label);
This works .

But this one does not :

W_qtutil w_qt;
w_qt.time_start_crono(ui->my_label);


void W_qtutil::time_start_crono(QWidget *indicador) {
m_timer = new QTimer();
m_timer->setInterval(1000);
QObject::connect(m_timer, SIGNAL(timeout()), this, SLOT(time_update_crono()));
m_timer->start();
}
(m_timer is public, and declared at .h section)

Any idea ?

agarny
1st March 2011, 14:00
In the case that doesn't work, I would imagine that the reason is that w_qt gets out of scope before your timer has time to emit its timeout signal.

tonnot
1st March 2011, 15:25
Thanks
So, If I use the *var = new ... it means that my object are going to live outside of the method where it was created?

mcosta
1st March 2011, 15:35
Sorry, but you need to study about C++ and only later about Qt.

You have to know about stack variables and heap variables.

agarny
1st March 2011, 15:35
Thanks
So, If I use the *var = new ... it means that my object are going to live outside of the method where it was created?Yes, and unless you free it, it will become what we call a memory leak (i.e. the kind of thing that should be avoided at all costs). Please note that Qt widget classes may be instantiated by providing a parent to the widget (http://doc.qt.nokia.com/latest/qwidget.html#QWidget). So, unless you don't provide a parent, the widget object will be automatically freed when its parent is deleted.

tonnot
1st March 2011, 17:41
Thanks agarny.
And I can be sure that an object that has parent is destroyed when the parent die ? Or have I to delete it ?

agarny
1st March 2011, 18:30
If you were to check the source code (http://qt.gitorious.org/qt/qt/blobs/4.7/src/gui/kernel/qwidget.cpp) (on line 1643), you would realise that this is exactly what it does...

ChrisW67
2nd March 2011, 00:02
Thanks agarny.
And I can be sure that an object that has parent is destroyed when the parent die ? Or have I to delete it ?

If a heap-allocated QObject (QTimer is one) has a parent QObject then it will be deleted when the parent is deleted. You can still delete the child manually if you want. A QObject without a parent is like any other C++ object with regard to lifetime: scoped if allocated on the stack, or until deleted if on the heap.