Search code examples
qtqwidgetqlistwidget

Access QWidget and child widgets from Qlistwidget


I have QListWidget and i'm filling items like below :

    QWidget *widget = new QWidget;
    QLabel *label = new QLabel(part);
    QLineEdit *line = new QLineEdit("1");
    line->setFixedWidth(50);


    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(label);
    layout->addWidget(line);
    layout->addStretch();

    widget->setLayout(layout);


    QListWidgetItem* new_item = new QListWidgetItem();
    new_item->setSizeHint(widget->sizeHint());
    ui->listPart->addItem(new_item);
    ui->listPart->setItemWidget(new_item,widget);

it's looks like this :

enter image description here

I'm trying to access my Qwidgets in QListwidgetitem and get data from label and lineedit.

I actually tried this but it's crashing and not giving any error :

  QWidget *widget = qobject_cast<QWidget*>(ui->listPart->itemWidget(ui->listPart->item(0)));
  QLabel* lbl = widget->findChild<QLabel*>("label");
  qDebug() << lbl->text();

Solution

  • From what I can see you are not giving the objectName at the QLabel when you create it. Try to add this label->setObjectName("label") after you create the label. Then you should find the child when you call widget->findChild<QLabel>("label");