Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QTableView is erasing cell content when I edit it



  • I've added a QTableView to a form and extended a QTableModel to handle the data that should be stored within the table. One of the columns contains string data and should be editable by the user. I've set things up so that the user can click a cell in the table, which causes an editor textbox to appear allowing the user to type in the content for the cell. However, when this editor box opens, it ignores any content already in the cell.

    Even if my cell has a word like 'orange' in it, when the user enters edit mode to change the value of the cell, the edit text box is empty. I would like the editor box to contain a copy of the cell's data as it currently exists in the table so the user can edit it rather than having to recreate it. Is there a way to do this?


  • Lifetime Qt Champion

    Then your TableModel does not return anything for Qt::EditRole.



  • I'm not sure what you mean. Qt::EditRole is a constant, not a method. I am checking for Qt::EditRole in setData() and it allows me to set the data properly, but is not called when the cell is preparing to be edited.

    
    bool DopeTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
    {
        if (role == Qt::EditRole)
        {
            const DopeRow& row = _rows[index.row()];
            DopeRow newRow = row;
    
            switch (index.column())
            {
            case 2:
                newRow.phoneme = value.toString();
                break;
            case 3:
                newRow.notes = value.toString();
                break;
            }
            _rows[index.row()] = newRow;
            dataChanged(index, index);
    
            return true;
        }
        return false;
    }
    

  • Lifetime Qt Champion

    Hi,

    Did you also re-implement the data method ? If so, how are you handling the EditRole there ?



  • @SGaist I have now, and it's working. Thanks.


Log in to reply