PDA

View Full Version : QAbstractProxyModel and QTreeView



niko
18th January 2008, 20:51
I want to create a Proxy Model - as a first step I tried to create a Proxy that should behave exaclty like the sourceModel:


class Proxy : public QAbstractProxyModel
{
Q_OBJECT

public:

Proxy(QObject* parent = 0) : QAbstractProxyModel(parent) { }

QModelIndex mapFromSource ( const QModelIndex & sourceIndex ) const
{
return sourceIndex;
}

QModelIndex mapToSource ( const QModelIndex & proxyIndex ) const
{
return proxyIndex;
}

int rowCount(const QModelIndex& parent) const
{
return sourceModel()->rowCount(parent);
}

int columnCount(const QModelIndex& parent) const
{
return sourceModel()->columnCount(parent);
}

QModelIndex index(int row, int col, const QModelIndex& parent) const
{
return sourceModel()->index(row, col, parent);
}
QModelIndex parent(const QModelIndex& index) const
{
return parent(index);
}
};

So far one thing is unclear to me: why do I have to implement rowCount, columnCount, index and parent? Why isn't this done in QAbstractProxyModel?

when using my proxy with the simpletreemodel-example this way:


int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(simpletreemodel);

QApplication app(argc, argv);

QFile file(":/default.txt");
file.open(QIODevice::ReadOnly);
TreeModel model(file.readAll());
file.close();

Proxy proxy;
proxy.setSourceModel(&model);

QTreeView view;
view.setModel(&proxy);
view.setWindowTitle(QObject::tr("Simple Tree Model"));
view.show();
return app.exec();
}

I get a messed-up tree - see attached screenshot.
Using a QTableView however works!

please help :D
niko

jpn
18th January 2008, 20:57
What do you intend to do with the proxy model?

niko
18th January 2008, 21:03
I'm writing a KDeveop4 plugin.

I have an existing model (the ProjectModel) and need one that displays all project-items just as the ProjectModel and makes the items checkable. So I wanted to re-implement flags(), setData() and data() - where I handle myselfe the checkbox-stuff - and forward the rest to the ProjectModel.

Or is there a better way?

thanks,
niko

jpn
18th January 2008, 21:08
You could simply use QSortFilterProxyModel which saves you from writing any of those methods. Just reimplement flags() and you're done.

niko
18th January 2008, 21:11
thanks, QSortFilterProxyModel works.

However I don't understand why my proxy didn't...

jpn
18th January 2008, 21:17
Notice that every QModelIndex belongs to a certain model. The view doesn't know there's proxy model in between. Besides other possible logical mistakes, the view only sees a model which returns indexes belonging to some other unknown model.