13.3.2.  Editable Models

[ fromfile: tablemodels.xml id: editablemodels ]

Example 13.16. src/libs/actioneditor/actiontablemodel.cpp

[ . . . . ]

Qt::ItemFlags ActionTableModel::
flags(const QModelIndex& index) const {
    if (index.isValid()) return Qt::ItemIsEnabled;
    else return 0;
}

Example 13.17. src/libs/actioneditor/actiontablemodel.cpp

[ . . . . ]

bool ActionTableModel::
setData(const QModelIndex& index, const QVariant& value, int role) {
    if (role != Qt::EditRole) return false;
    int row = index.row();
    if ((row < 0) | (row >= m_actions.size())) return false;
    QString str = value.toString();
    QKeySequence ks(str);
    QAction* previousAction = 0;

    if (ks != QKeySequence() ) foreach (QAction* act, m_actions) {
        if (act->shortcut() == ks) {
            previousAction = act;
            break;
        }
    }
    if (previousAction != 0) {
        QString error = tr("%1 is already bound to %2.").
                arg(ks.toString()).arg(previousAction->text());
        bool answer = QMessageBox::question(0, error,
                    tr("%1\n Remove previous binding?").arg(error),
                    QMessageBox::Yes, QMessageBox::No);
        if (!answer) return false;
        previousAction->setShortcut(QKeySequence());
    }
    m_actions[row]->setShortcut(ks);
    QModelIndex changedIdx = createIndex(row, 1);   1
    emit dataChanged(changedIdx, changedIdx);       2
    return true;
}

1

Column 1 displays the shortcut.

2

Required for Views to know when/what to update.


Example 13.18. src/libs/actioneditor/actiontableeditor.cpp

[ . . . . ]

void ActionTableEditor::
on_m_tableView_activated(const QModelIndex& idx) {
    int row = idx.row();
    QAction* action = m_model->action(row);
    ActionEditorDialog aed(action);

    int result = aed.exec();
    if (result ==  QDialog::Accepted) {
        QKeySequence ks = aed.keySequence();
        m_model->setData(idx, ks.toString());
        m_changedActions << action;
    }
}

Example 13.19. src/libs/actioneditor/actiontableeditor.cpp

[ . . . . ]

void ActionTableEditor::accept() {
    QSettings s;
    s.beginGroup("shortcut");
    foreach (QAction* act, m_changedActions) {
        s.setValue(act->text(), act->shortcut() );
    }
    s.endGroup();
    QDialog::accept();
}