Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you put QWidgets on the stack?

Backstory:

I had some of my code reviewed, and I had made a local QMessageBox for displaying an error, and allocated it to the heap:

if (getAutopilotList.error() == 0) {
    QMessageBox* error = new QMessageBox(0);
    error->setDetailedText(getAutopilotList.errorString());
    error->setText("something");
    error->setWindowTitle(tr("Error!"));
    error->show();
    return;
}

The developer said:

This pointer will leak, you are setting no parent and you never delete it. Here as well you do not need a pointer. As for the parent do not use 0, but Core::ICore::mainWindow().

I was confused because I thought:

  1. QWidgets only worked on the Heap
  2. That the pointer would delete error; automatically when the messagebox was closed.

I tried putting the QMessageBox on the stack, but it did not show.


Questions:

  1. Can I put this QMessageBox on the stack and have it work, and should I?
  2. Do I need to explicitly delete the QMessageBox pointer?
  3. Why is setting the parent to something beyond 0 important in this case?
like image 721
Anon Avatar asked Dec 19 '22 03:12

Anon


2 Answers

In principle, you can create a QWidget object on the stack. Here, it wouldn't work because the call to error->show() does not show the message box immediately, it just schedules a display when back to the main even loop, at which time the object will be destroyed. For that reason, deleteing the QMessageBox is not going to work either. Setting the parent gives the responsability of the object destruction to the parent, when the parent is itself destroyed, and it is a good idea.

However, if I understand what you want to do, you want to wait for the user to click on the OK button before the return. If that's the case, you'd better use the static QMessageBox functions, such as QMessageBox::warning.

If you want a persistent message box, then your code is OK, but you should add the following call:

error->setAttribute(Qt::WA_DeleteOnClose);

This will trigger deletion when the corresponding window is closed.

like image 162
Vincent Fourmond Avatar answered Dec 21 '22 16:12

Vincent Fourmond


I tried putting the QMessageBox on the stack, but it did not show.

Because it will get destroyed immediately when thread goes out of the scope. You had to use QMessageBox::exec() to run it in block-mode.

like image 31
Victor Polevoy Avatar answered Dec 21 '22 16:12

Victor Polevoy