Search code examples
c++qtqtreeview

QTreeView: How to check children after checking parent


I'm writing an application with QtCreator and am trying to check the children of a checked parent but can't seem to be able to find the correct way to do it.

I setup the model this way:

MyClass::MyClass()
{
    QVBoxLayout *layout = new QVBoxLayout;

    setWindowTitle(tr("Menu"));
    m_model = new QStandardItemModel (this);

    addItems(m_model);

    m_view = new QTreeView;
    m_view->header()->hide();
    m_view->setModel(m_model);
    m_view->setContextMenuPolicy(Qt::CustomContextMenu);

    layout->addWidget(m_view);
    layout->setMargin(0);
    setLayout(layout);

    connect(m_view, SIGNAL(customContextMenuRequested(QPoint)),
             this, SLOT(contextMenuRequested(QPoint)));
}

I have tried with the signal clicked() and a custom slot but can't figure out how to check the children of the checked parent.

Any advice would be appreciated.


Solution

  • Implement a slot for the clicked signal of your QTreeView and make sure to set the itens you want checkable in your addItens function using QStandardItem::setCheckable.

    void MyClass::on_treeView_clicked(const QModelIndex &index) {
        QStandardItem* l_itemClicked = m_model->itemFromIndex(index);
    
        if (!l_itemClicked->rowCount()) return; // clicked item has no children
    
        for (int i = 0 ; i < l_itemClicked->rowCount() ; ++i) {
            QStandardItem* l_child = l_itemClicked->child(i);
            bool l_isChecked = l_child->checkState() == Qt::Checked;
    
            if (l_child->isCheckable())
                l_child->setCheckState(l_isChecked ? Qt::Unchecked : Qt::Checked);
        }
    }