Reputation: 6147
How do i set the checkbox for the selected Treeview items in my QTreeview C++ project?
My goal is to iterate over the selected Treeview items and set their checkbox state to true or false. I'll be doing this through a righclick menu. I just don't know how to collect the selected items.
I wrote a function that loops through all the items and sets the checkboxes to true or false, but I'm struggling to figure out how to set only the selected items.
void ShotsEditor::checkAll()
{
for (int i = 0; i < d->sourceModel->rowCount(); i++){
QStandardItem* item = d->sourceModel->item(i);
if (item->isCheckable())
{
item->setCheckState(Qt::Checked);
}
else{
if (item->hasChildren())
{
for (int j = 0; j < item->rowCount(); j++){
QStandardItem* item1 = item->child(j);
if (item1->isCheckable())
{
item1->setCheckState(Qt::Checked);
}
}
}
}
}
}
This is where I'm stuck...
void ShotsEditor::checkSelected()
{
QModelIndexList selected = d->treeView->selectionModel()->selectedIndexes();
qDebug() << "selected indexes" << selected;
foreach (QModelIndex index, selected)
{
if (index.column()==0)
{
int row = index.row();
qDebug() << "row" << row;
}
}
}
This is how i would do it in pyside. I don't know how to do it in c++
def set_checked(self):
indexes = self.treeview.selectedIndexes()
for i in indexes:
model = i.model()
item = i.model().itemFromIndex(i)
print i, model, item
if item.isSelectable():
item.setCheckState(QtCore.Qt.Checked)
Upvotes: 0
Views: 3220
Reputation: 6147
For those who have this same problem:
QModelIndexList selected = d->treeView->selectionModel()->selectedIndexes();
qDebug() << "selected" << selected;
foreach (QModelIndex index, selected)
{
QStandardItem* item = d->sourceModel->itemFromIndex(index);
qDebug() << "item" << item;
if (item->isSelectable() && item->isCheckable())
{
item->setCheckState(Qt::Unchecked);
}
}
Upvotes: 0
Reputation: 243917
The proper way to get the items selected is overwriting the selectionChanged
slot, it returns the selected and deselected items, then we get the items through the indexes and check them.
class TreeView : public QTreeView
{
Q_OBJECT
protected slots:
void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected){
Q_UNUSED(deselected)
const auto *m = qobject_cast<QStandardItemModel *>(model());
if(m){
for(const auto index: selected.indexes()){
m->itemFromIndex(index)->setCheckState(Qt::Checked);
}
}
}
};
#include "main.moc"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TreeView w;
QStandardItemModel *model = new QStandardItemModel;
for (int i = 0; i < 4; ++i){
QStandardItem *parent =new QStandardItem(QString("Family %1").arg(i));
for (int j = 0; j < 4; ++j){
QStandardItem *child = new QStandardItem(QString("item %1").arg(j));
parent->appendRow(child);
}
model->appendRow(parent);
}
w.setModel(model);
w.show();
return a.exec();
}
The complete example you find in the following link
Upvotes: 2