Reputation: 48966
When working with Qt
widgets (i.e; QLabel), why do we use pointers?
For example, why do we write:
QLabel *label = new QLabel("Hello");
And, not:
QLabel label = new QLabel("Hello");
?
Thanks.
Upvotes: 2
Views: 1905
Reputation: 9749
If you want to define a var without a pointer, it looks like QLabel label
;
The label we got:
In c++ a var will only be object-oriented if you use it via a pointer or a reference. Qt is a object-oriented class library, so this is why QLabel
is defined with a pointer.
Upvotes: -1
Reputation: 11
Just to be complete, there is no reason why you shouldn't allocate some widgets on the stack. This is especially handy for objects with a limited lifespan, like context menu's and modal dialogs where you have to wait on the result. On these widgets you normally call exec(), which blocks until the user closes it.
Upvotes: 0
Reputation: 1768
I think this is not a Qt problem, this should be a question of C++ programming. You maybe use Java before, as java don't have pointer concept. My suggestion, find a C++ book and learn the basic concept and usage about what's the meaning for a C++ pointer before you try to use C++ and Qt.
Upvotes: 3
Reputation: 20282
new
returns a pointer. If you create an object via dynamic memory allocation - you obviously have to use a pointer.
QLabel label = new QLabel("Hello");
is incorrect code and will not compile.
Why do you use dynamic allocations for widgets? Because they have to be alive between function calls, as with any event driven GUI system. Allocations on stack (local objects) will be deallocated at the end of the scope, which wouldn't work well with widgets.
Upvotes: 9
Reputation: 24846
Because if you will create them on a stack they will be deleted after end of scope.
If you will write something like this:
void foo()
{
QWidget windget;
}
widget will be removed after foo() is terminated. If using new
it will live until it will be deleted manually (usually by parent Widget).
I don't think QLabel label = new QLabel("Hello");
will even compile. Possibly you ment
QLabel label("Hello");
Upvotes: 8