PDA

View Full Version : some of QModel to QModel



baray98
30th October 2007, 03:46
I made a model , a tree model to be precised and I want to copy an item in my tree including its children. What is the easiest and cleanest solution to this, I tried searching but wasn't able to find some samples. To the guru's please help the novice out

baray98

jpn
30th October 2007, 07:54
Here's a small example which is capable of copying and pasting selected items. Unfortunately it doesn't take children into account, but that should be "only" a matter of reimplementing QAbstractItemModel::mimeData() and QAbstractItemModel::dropMimeData(). :)


#include <QtGui>

class TreeView : public QTreeView
{
protected:
void keyPressEvent(QKeyEvent *event)
{
if (event == QKeySequence::Copy)
{
QModelIndexList indexes = selectionModel()->selectedIndexes();
QMimeData *data = model()->mimeData(indexes);
QApplication::clipboard()->setMimeData(data);
event->accept();
}
else if (event == QKeySequence::Paste)
{
QModelIndex index = currentIndex();
const QMimeData *data = QApplication::clipboard()->mimeData();
if (model()->dropMimeData(data, Qt::CopyAction, index.row() + 1, index.column(), index.parent()))
setCurrentIndex(index.sibling(index.row() + 1, index.column()));
event->accept();
}
else
{
QAbstractItemView::keyPressEvent(event);
}
}
};

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QStandardItemModel model;
QStandardItem *parentItem = model.invisibleRootItem();
for (int i = 0; i < 4; ++i) {
QStandardItem *item = new QStandardItem(QString("item %0").arg(i));
parentItem->appendRow(item);
parentItem = item;
}

TreeView view;
view.setModel(&model);
view.show();
return app.exec();
}