3

I want to create same kind of QTreeView (not QTreeWidget) structure as shown in attached figure.. This is Property Editor of QT. I am using QT-4.6

enter image description here

On 2nd column, depending on different condition, I can have either a spin box, or a drop down or a checkbox or text edit... and so on... Please guide me on how to set different delegates in different cells of a particular column. From docs, it is evident that there is no straight away API for setting delegate on a cell (rather is available for full widget or a row or a column).

4

2 回答 2

5

All QAbstractItemDelegate methods, like createEditor or paint, have a model index as one of their parameters. You can access model data using that index and create an appropriate delegate widget. When you create your model you should set some value to every item that will be used to distinguish its type.

An example:

enum DelegateType
{
    DT_Text,
    DT_Checkbox,
    DT_Combo
}

const int MyTypeRole = Qt::UserRole + 1;

QStandardItemModel* createModel()
{
    QStandardItemModel *model = new QStandardItemModel;

    QStandardItem *item = new QStandardItem;
    item->setText("Hello!");
    item->setData(DT_Checkbox, MyTypeRole);

    model->appendRow(item);

    return model;
}

QWidget* MyDelegate::createEditor(QWidget *parent, 
                                  const QStyleOptionViewItem &option, 
                                  const QModelIndex &index) const
{
    int type = index.data(MyTypeRole).toInt();

    // this is a simplified example
    switch (type)
    {
    case DT_Text:
        return new QLinedEdit;
    case DT_Checkbox:
        return new QCheckBox;
    case DT_Combo:
        return new QComboBox;
    default:
        return QItemDelegate::createEditor(parent, option, index);
    }
}
于 2016-02-05T19:27:30.483 回答
1

@hank This is in response to your last comment... Do you see any flaw in it ?

   MyItem* item2 = new MyItem(second);
    item2->setData(delType, **MyTypeRole**);
    if(delType == DT_Combo)
    {
        QString str1, str2, str3;
        QStringList abc ;
        abc << ("1" + str1.setNum(counter) ) << ("2" + str2.setNum(counter) )<< ( "3" + str3.setNum(counter) );
        item2->setData(abc, MyTypeRole1);
    }

QWidget* MyDelegate::createEditor(QWidget *parent, 
                                  const QStyleOptionViewItem &option, 
                                  const QModelIndex &index) const
{
    int type = index.data(MyTypeRole).toInt();

    // this is a simplified example
switch (type)
{
case DT_Text:
    return new QLinedEdit;
case DT_Combo:
{
QComboBox* cb = new QComboBox(parent);
QStringList entries - index.data(MyTypeRole1).toStringList();
cb->addItems(entries)
return cb;
}


On different item2, I dynamically create entries with a counter variable that is different everytime it comes here... Here, different combo boxes display different entries.
Does the approach looks fine to you ?

于 2016-02-06T08:59:17.353 回答