PDA

View Full Version : Why can I only show a QLabel by declaring it as a pointer?



tom989
16th November 2012, 14:20
This code displays text on my qwidget:




QLabel *button = new QLabel(this);
button->setText("dog");
button->show();



but this does not:



QLabel button (this);
button.setText("dog");
button.show()



I'm a bit confused why.

Thanks!

high_flyer
16th November 2012, 14:30
It has nothing to do with the way you allocate it, more likely its a scope problem.
Show the full code.

tom989
16th November 2012, 14:38
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setFixedSize(QSize(700,300));

QLabel label (this);
label.setText("dog");
label.show();



}

Lesiok
16th November 2012, 15:00
Basics of C / C + +. What happens to an object label after leaving the Widget constructor?

tom989
16th November 2012, 15:15
It gets destroyed!

Still not sure why a pointer helps though.

Lesiok
16th November 2012, 16:23
Once more basics of C/C++ : because deleting of pointer DON'T destroy object.

tom989
16th November 2012, 17:08
Calm down. Oh and C isn't relevant here because it has no classes/objects.

Zlatomir
16th November 2012, 18:04
Oh and C isn't relevant here because it has no classes/objects.
C also has something to do with issue like this because it has functions that have scope (constructor is also function).

Anyway a small explanation about Lesiok's comment, a better way to say is: pointer getting out of scope doesn't destroy the object (i talk about normal pointers not the smart ones obviously) - don't confuse what he said with calling C++'s delete pointer.
So:
1) when you allocate the object in a function scope it get destroyed at the end of scope (so it doesn't has a chance to actually show on screen)
and
2) when you use a pointer you allocate the object on the heap and only the pointer gets out of scope (the actual object still exist and it will be showed eventually) //this practice (to let the pointer to a heap object go out of scope without calling delete) is usually not a good idea - but Qt has the parent-child mechanism that keep a (copy of) the pointer and will delete it when the parent will be deleted (or goes out of scope). You can read a little more about parent-child in QObjects here (http://doc.qt.digia.com/qt/objecttrees.html) and also i recommend to read a C++ book (search of "Thinking in C++" and you will find two free volumes that are free to download)

wysota
17th November 2012, 06:35
Calm down. Oh and C isn't relevant here because it has no classes/objects.

Of course C has objects. And the issue is not related to "classes" since if you had an "int" here, it would behave exactly the same way.


Calm down. Oh and C isn't relevant here because it has no classes/objects.

Of course C has objects. And the issue is not related to "classes" since if you had an "int" here, it would behave exactly the same way.