Search code examples
c++qtcompiler-errorsqlistwidgetqlistwidgetitem

How to Check all items in a QLlistWidget?


I have a QListWidget with items that have a checkbox, I want to iterate throiugh all of them and mark them checked, I tried this:

void ScaperDialog::CheckAll(void) {
    dbg_prnt << "inside " << __func__ <<std::endl;
    QListWidget *list = parentWidget()->findChild<QListWidget *>();
    if (!list)
        std::cerr << "No QListWidget found" << std::endl;

    QList<QListWidgetItem *> items = list->findChildren<QListWidgetItem *>();
    QList<QListWidgetItem *>::iterator i;
    for (i = items.begin();i != items.end(); i++) {
        dbg_prnt << (*i)->text.ToString() << std::endl;
    }
}

but get a compiler error: error: ‘i.QList::iterator::operator*()->QListWidgetItem::text’ does not have class type dbg_prnt << (*i)->text.ToString() << std::endl; this obviously is only to print each element, to get it marked, I would do (*i)->setChecked(true); instead of printing it but I think this will give me the same error.

How do I get this rolling?


Solution

  • QListWidgetItem are not QObjects so you can not access through findChildren() method, what you should use is the count() and item() method of QListWidget:

    void ScaperDialog::CheckAll(void) {
        dbg_prnt << "inside " << __func__ <<std::endl;
        QListWidget *list = parentWidget()->findChild<QListWidget *>();
        if (!list)
            std::cerr << "No QListWidget found" << std::endl;
    
        for(int i=0; i < list->count(); ++i){
            QListWidgetItem *it = list->item(i);
            dbg_prnt << it->text().toStdString() << std::endl;
            it->setFlags(it->flags() | Qt::ItemIsUserCheckable);
            it->setCheckState(Qt::Checked);
        }
    }