QTreeView vs setIndexWidget

2019-07-25 17:25发布

问题:

I am using QStandardItemModel with QStandardItem's.

I don't want to write my own model and any delegates.

I just want to have tree of checkboxes with QComboBox'es in second column...

m_model->setColumnCount(2);
for (int i = 0; i < sectionCount; i++)
{
    QStandardItem * section = new QStandardItem(tr("Section %1").arg(i+1));
    section->setCheckable(true);
    section->setCheckState(Qt::Checked);

    for (int j = 0; j < itemsCount; j++)
    {
        QStandardItem * item = new QStandardItem(tr("Item %1").arg(j+1));
        item->setCheckable(true);
        item->setCheckState(Qt::Checked);

        QStandardItem * item2 = new QStandardItem("xxx");

        section->appendRow(QList<QStandardItem*>() << item << item2);

        QComboBox * combo = new QComboBox();
        QModelIndex index = m_model->index(j, 1, );

        // HERE i have index = {-1;-1}

        ui->treeView_options->setIndexWidget(index, combo);
    }
    m_model->appendRow(section);
}

Is it possible to use setIndexWidget this way?

UPDATE:

I have no QComboBox in second column... Why?

回答1:

Nope, won't work:

This function should only be used to display static content within the visible area corresponding to an item of data. If you want to display custom dynamic content or implement a custom editor widget, subclass QItemDelegate instead.



回答2:

it is possible actually. I would recommend first creating a model with two columns. Create the items in a row and append it to the model. Only after you appended the row with items you can call view->setIndexWidget(), with your combobox content. It worked for me, and I have dynamic content. ItemDelegates are more complicated, I would recommend setIndexWidget() - worked for me just fine.