C++ – How to edit a QTableView

cmodel-view-controllerqt4

I am currently trying to add editing functionality to a class derived from QTableView. I have added a custom delegate that should provide editing functionality. However if I do a simple qDebug() << "FieldDelegate::createEditor()"; at the beginning of the delegate, I can see that this function never get's called. I tried to look at the examples in the Qt4 documentation and in the book "C++ Gui Programming with QT4", but all I could find were examples for delegates with QTableWidgets and not QTableViews. However in my case I need a custom data model, so I do not want to replicate any data in QTableWidgetItems.

So far I did the following:

  • I added the custom delegate using QAbstractItemModel::setItemDelegate()
  • I activated editing functions using setEditTriggers( QAbstractItemView::DoubleClicked )

When I double click on an item nothing happens in this setup. The FieldDelegate::createEditor() is not called at all.

I also tried connecting the doubleClicked() signal from the QAbstractItemView to the edit() slot of the same class, but this only gives me the message edit: editing failed whenever I double click on a cell.

So far I do not return anything in other roles than Qt::EditRole from the DatabaseModel::data() method. This will be similar to the final case, where I want to add an empty row at the bottom of the table that will be used for adding new data. Could this cause the problem?

Here is the code for the construction of the View:

DocumentChoiceView::DocumentChoiceView( DatabaseModel * model,
                                          QWidget * parent ) :
    QTableView( parent ),
    m_model( model )
  {
    setShowGrid ( false );
    setModel( m_model );
    setItemDelegate( m_model->delegate().get() );
    setEditTriggers( QAbstractItemView::DoubleClicked );
    connect( this, SIGNAL(doubleClicked(const QModelIndex&)), 
             this, SLOT(edit(const QModelIndex&)) );
    verticalHeader()->hide();
  }

Best Answer

For the model to be editable the edit flag need to be returned.

//Reimplement 
Qt::ItemFlag QAbstractItemModel::flags ( const QModelIndex & index ) const;
//and add 
Qt::ItemIsEditable 
//to the returned value

http://doc.qt.io/qt-4.8/model-view-programming.html#making-the-model-editable

Related Topic