如何检查 QListWidget 中的所有项目?

How to Check all items in a QLlistWidget?

我有一个带有复选框的项目的 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;

    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;
    }
}

但出现编译错误: 错误:‘i.QList::iterator::operator*()->QListWidgetItem::text’没有class类型 dbg_prnt << (*i)->text.ToString() << std::endl; 这显然只是打印每个元素,为了标记它,我会做 (*i)->setChecked(true); 而不是打印它,但我认为这会给我同样的错误。

如何滚动?

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);
    }
}