Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt widgets and pointers

Tags:

c++

pointers

qt

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.

like image 297
Simplicity Avatar asked Mar 17 '26 20:03

Simplicity


1 Answers

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.

like image 148
littleadv Avatar answered Mar 19 '26 11:03

littleadv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!