Search code examples
c++qtqlistview

Exclusive checkbox in QListView


I'm trying to do exclusive checkboxes as a QListView items. I'm using QStandardItemModel as a model with QStandardItem's.

I'm adding items to the list dynamically and set it checkable:

QStandardItem *item = new QStandardItem(treeView->model()->data(index).toString());
item->setCheckable(true);
m_categoriesModel->appendRow(item);

I tried connect all items to QSignalMapper but QStandardItem doesn't have checked(bool) signal (basically it does not have any).

Is there any way to solve the problem?


Solution

  • You can always make it in the way described below. Firstly connect the clicked signal of ListView to the slot which will handle your items click. Secondly inside of the slot you can get the item from QModelIndex and check the state of the item. Below is pseudo code:

    For example, in constructor of ListView:

      connect(this, SIGNAL(clicked(QModelIndex)), this, SLOT(_handleItemClicked(QModelIndex)));
    

    Slot of ListView:

    void ListView::_handleItemClicked(QModelIndex index)
    {
            QStandardItem* item = _model->itemFromIndex(index);
    
            if( item->checkState() == Qt::Checked) qDebug() << "Checked!";
    }