0

Either one of method the slot/method will allocate memory on heap then how do I suppose to delete it in the destructor?

Test::~Test()
{
    delete frame;
    delete frame_2;
    delete ui;
}

void Test::on_pushButton_clicked()
{
    frame = new QFrame();
    frame->show();
}

void Test::on_pushButton_2_clicked()
{
    frame_2 = new QFrame();
    frame_2->show();
}

Actually I want to build a app that has multiple buttons, each button allocates different QFrame. Or my coding design for situation like this is wrong?

Thank you.

yssh
  • 29
  • 5
  • You may initialize them to `nullptr` in the constructor, since it's fine to use `delete` on a null pointer. See [Is it still safe to delete nullptr in c++0x?](https://stackoverflow.com/q/6731331/12122460) – kotatsuyaki Jun 06 '22 at 04:27
  • You could try to use `std::uniqe_ptr`. They automatically call delete for pointers, although im not entirely sure right now if they work with `nullptr`, correct me if im wrong. – Hydrated Dragon Jun 06 '22 at 06:32
  • 2
    Please also note that `Qt` has its own [object ownership model](https://doc.qt.io/qt-5/objecttrees.html) that may well render the issue moot. – G.M. Jun 06 '22 at 08:33
  • Assigning `nullptr` worked out very well. – yssh Jun 06 '22 at 18:50

1 Answers1

1

The Qt way would be to pass a pointer to a parent whenever you new-up a QtObject. Qt will automatically destroy an object's children when it is destroyed. You should never have to call delete.

So, assuming Test is a QtObject subclass, you can change your code to the following:

Test::~Test() = default;

void Test::on_pushButton_clicked()
{
    frame = new QFrame(this);
    frame->show();
}

void Test::on_pushButton_2_clicked()
{
    frame_2 = new QFrame(this);
    frame_2->show();
}

Also check out this article on ownership with Qt for more deets: https://doc.qt.io/qt-5/objecttrees.html

  • In most real-world code, the `QFrame` objects would typically be added to a `QLayout` of some sort, and their ownership would be implicitly transferred to the object associated with that QLayout by the `theLayout->addWidget()` call. At least, that's how modern versions of Qt prefer people to do it. – Jeremy Friesner Jun 07 '22 at 06:00
  • If I delete `theLaout` object then, whats inside `QFrame` will be automatically deleted without calling delete? But what if `QFrame` have other dynamic variables like a dynamic vector which is a part of backend logic? – yssh Jun 07 '22 at 16:28
  • A vector which has references of other dynamic `QWidgets`, And I want to delete it from `QFrame`. – yssh Jun 07 '22 at 18:31