Search code examples
c++qtqlistwidgetqt-signalsqlistwidgetitem

Adding QListWidgetItem To QListWidget


So I have a class SnapshotPanel : public QListWidget that I am trying to add a QListWidgetItem to dynamically, however it when ever I try I get a segfault. I have verified that my code to add the item is correct as I can add to the list when I construct my SnapshotPanel. However I cannot add to the panel when the code is called via signals and slot, insight into what I am missing would be apprecited.

Here is the constructor:

SnapshotPanel::SnapshotPanel(QWidget *parent):QListWidget(parent)
{

  this->setViewMode(QListWidget::IconMode);
  this->setIconSize(QSize(256,256));
  this->setResizeMode(QListWidget::Adjust);

  QIcon icon("icon.jpeg");
  QListWidgetItem *widget = new QListWidgetItem(icon,"Earth");

  this->addItem(widget);
}

So is there any reason I wouldn't be able to use the following code when called via signals and slots:

{
  QIcon icon("icon.jpeg");
  QListWidgetItem *widget = new QListWidgetItem(icon,"Earth");
  this->addItem(widget);
}

Solution

  • I think it should just work. "Slots are normal C++ functions" according the documentation.

    If you are using multiple threads you need to look into the connection mechanism. Perhaps you need to use queued connections. You would change your connect statements from:

    connect(button, &QPushButton::clicked, this, &MainWidget::on_button_clicked);
    

    to

    connect(button, &QPushButton::clicked, this, &MainWidget::on_button_clicked, Qt::QueuedConnection);
    

    But read the official documentation here. A SO question (basically pointing you back to the documentation) is here.