An Useful Model Proposal : KStringDataListModel

Benjamin Meyer ben at meyerhome.net
Mon Mar 5 09:04:53 GMT 2007


On Friday 02 March 2007 12:36, Bruno Virlet wrote:
> Hello !
>
> On Thursday 01 March 2007, David Faure wrote:
> > > At the risk of asking the obvious: Why not simply use a
> > > QStandardItemModel?
> > > [...]
> >
> > Hmpf. I admit that I didn't think of doing it that way.
>
> I ported my model to use QStandardItemModel. It is actually nicer.
>
> Please find the patch attached.
>
> Bruno

+QString KStringDataListModel::label(const QModelIndex &index) const
+{
+    if (!index.isValid())
+        return QString();
+
+    return itemFromIndex( index )->text();
+}
[snip]

label and internal can be simplified to one liners, the model will return a 
QString() if index isn't valid.
QString KStringDataListModel::label(const QModelIndex &index) const {
	return index.data().toString();
}
QString KStringDataListModel::internal(const QModelIndex &index) const {
	return index.data(Qt::UserRole+1).toString();
}

+QModelIndex KStringDataListModel::insertRow( const QString &label, const 
+QVariant &internalData, const QModelIndex &index)
+{
+    QStandardItem *item = new QStandardItem(label);
+    item->setData(internalData);
+
+    if (index.isValid())
+    {
+        beginInsertRows(QModelIndex(), index.row() + 1, index.row() + 1);
+        QStandardItemModel::insertRow( index.row() + 1,  item);
+        endInsertRows();
+    }
+    else
+        appendRow( i );
+
+    return indexFromItem(i);
+}

insert rows does not need to do the begin/end and this model and in fact it 
would probably break things.  Also because it is only to be a list it can be 
simplified further to not have to worry about the parent.

QModelIndex KStringDataListModel::insertRow( const QString &label, const 
QVariant &internalData, const QModelIndex &index)
{
    QStandardItem *item = new QStandardItem(label);
    item->setData(internalData, Qt::UserRole+1);
    insertRow(rowCount() + 1,  item);
    return indexFromItem(item);
}

+void KStringDataListModel::moveUp( const QModelIndex &index )
+{
+    if (!index.isValid() || index.row() == 0)
+        return;
+
+    emit layoutAboutToBeChanged();
+    QList<QStandardItem*> items = takeRow(index.row() - 1);
+    QStandardItemModel::insertRow( index.row(),  items );
+    emit layoutChanged();
+ }

You shouldn't use the signals which would just cause extra repainting and 
layouting.  You can remove the checks making moveUp and moveDown one liners.

void KStringDataListModel::moveUp( const QModelIndex &index ) {
	 model->insertRow(index.row() - 1, model->takeRow(index.row()));
}

You could probably just have these be inline functions in the header.  At the 
end of the day there is not that much meat to the class other then the API

-Benjamin Meyer




More information about the kde-core-devel mailing list