0

I am using FlowLayout example of qt.

I added a context menu for all items in FlowLayout to enable renaming and removing. Renaming works, but whenever I call Remove, I receive a Segmentation Error.

Here is the removeSlot call:

  QAction *removeAction = new QAction(tr("Remove"), this);
  connect(removeAction, SIGNAL(triggered()), this, SLOT(removeSlot()));
  Menu->addAction(removeAction);

And emitting signal:

void FlowLayoutWidget::removeSlot()
{
  emit removeMe(m_ownId);
}

FlowWindow.cpp catches the signal and executes the following code:

void FlowWindow::removeItemAt(int _index)
{

  while(QLayoutItem* item = flowLayout->itemAt(_index))
  {
      QWidget* widget = item->widget();
      flowLayout->removeWidget(widget);
      delete widget;
      break;

  }
}

Whenever this function is called, I receive a segmentation error. How can I solve this?

www
  • 586
  • 1
  • 14
  • 29

1 Answers1

1

You're calling delete on an object from within a slot triggered by that object. That can sometimes be problematic, in ways that are not always obvious to predict. I suspect it may be causing your problem in this case. Qt provides the method QObject::deleteLater() which deals with this by scheduling the object for deletion after control returns to the event loop.

void FlowWindow::removeItemAt(int _index)
{

  while(QLayoutItem* item = flowLayout->itemAt(_index))
  {
      QWidget* widget = item->widget();
      flowLayout->removeWidget(widget);
      //delete widget; avoid this
      widget.deleteLater(); //try this instead
      break;

  }
}

See this question/answer for some more info.

Also, I will note that since you're deleting (or scheduling for deletion) the object, you shouldn't need to explicitly call flowLayout->removeWidget(widget) - it will be automatically taken care of when the object is destroyed.

Community
  • 1
  • 1
tmpearce
  • 12,523
  • 4
  • 42
  • 60
  • Thanks :). This solved segmentation error problem. Could you also tell me how can I get the index with `itemAt` to correctly remove the item? Can I iterate through flow layout? – www Jul 30 '13 at 10:09
  • That's a different topic, so it should be its own question. When you ask the question, make sure to show what you've tried and what you've discovered. (That may solve it all by itself.) – tmpearce Jul 30 '13 at 10:13
  • Ops. This was because of the index not being updated. Now everything is clear. – www Jul 30 '13 at 10:17