简体   繁体   中英

Qt widgets and pointers

When working with Qt widgets (ie; 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.

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.

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");

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.

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.

If you want to define a var without a pointer, it looks like QLabel label ; The label we got:

  • is located on the stack.
  • can not support polymorphism.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM