4

QAbstractItemModel を使用beginInsertRows()endInsertRows()て、基になるデータ ストアに行を挿入しています。begin メソッドと end メソッドの間でデータ挿入関数を呼び出します。ただし、私のデータの挿入関数は、データの制限により挿入が失敗する可能性があることを示す bool パラメーターを返します。挿入が失敗した場合、モデルとそれに関連付けられたビューは変更されません。これが発生した場合、行を挿入しないこと、または行の挿入を停止することをモデルに知らせるにはどうすればよいですか?

4

1 に答える 1

3

を継承するカスタムモデルを使用していると思いますQAbstractItemModel。その場合、insert メソッドを次のように記述できます。

bool CustomModel::insertMyItem(const MyItemStruct &i)
{
    if (alredyHave(i))
        return false;
    beginInsertRow();
    m_ItemList.insert(i);
    endInsertRow();
}

データメソッドは次のようになります。

QVariant CustomModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole || role == Qt::ToolTipRole)
    switch (index.column())
    {
        case INDEX_ID:
            return m_ItemList[index.row()].id;
        case INDEX_NAME:
            return m_ItemList[index.row()].name;
        ...
    }
    return QVariant();
}

最後に、入力方法は次のようになります。

void MainWindow::input()
{
    MyInputDialog dialog(this);
    if (dialog.exec() == QDialog::Rejected)
        return;
    myModel->insertMyItem(dialog.item());
}
于 2013-04-06T16:54:45.177 に答える