QWidget *TrackDelegate::createEditor(QWidget *parent,

                                     const QStyleOptionViewItem &option,
                                     const QModelIndex &index) const
{
    if (index.column() == durationColumn) {
        //QTimeEdit *timeEdit = new QTimeEdit(parent);
        QComboBox *timeEdit = new QComboBox(parent);
        //timeEdit->installEventFilter(const_cast<TrackDelegate*>(this));
        timeEdit->setObjectName("timeEdit");
//        timeEdit->setDisplayFormat("mm:ss");
//        connect(timeEdit, SIGNAL(editingFinished()),
//                this, SLOT(commitAndCloseEditor()));
        timeEdit->insertItem(0,"test1");
        timeEdit->insertItem(1,"test2");
        return timeEdit;
    } else {
        return QItemDelegate::createEditor(parent, option, index);
    }
}
void TrackDelegate::setEditorData(QWidget *editor,
                                  const QModelIndex &index) const
{
    if (index.column() == durationColumn) {
         QComboBox *timeEdit = qobject_cast<QComboBox *>(editor);
         timeEdit->setCurrentIndex(1);
//        int secs = index.model()->data(index, Qt::DisplayRole).toInt();
//        QTimeEdit *timeEdit = qobject_cast<QTimeEdit *>(editor);
//        timeEdit->setTime(QTime(0, secs / 60, secs % 60));
    } else {
        QItemDelegate::setEditorData(editor, index);
    }
}

void TrackDelegate::setModelData(QWidget *editor,QAbstractItemModel *model,
                                 const QModelIndex &index) const
{
    if (index.column() == durationColumn) {
//        QTimeEdit *timeEdit = qobject_cast<QTimeEdit *>(editor);
//        QTime time = timeEdit->time();
//        int secs = (time.minute() * 60) + time.second();
//        model->setData(index, secs);
    } else {
        QItemDelegate::setModelData(editor, model, index);
    }
}
上述三个方法是实现tableview编辑某个单元格出现控件的主要方法
其中第三个方法TrackDelegate::setModelData
是实现把编辑的控件发的数据写回到model中,但这个方法什么时候会调用?
当你编辑完控件后点击tableview其他单元格后会调用该方法
或者代码添加emit commitData(editor);就会立马执行该方法。
05-11 17:47