Tuesday, October 10, 2006

Dynamic Models

When creating a custom tree model in Qt one common request is to lazily populate the tree. Starting in 4.2 there is a nice way to do this using QAbstractitemModel's fetchMore(). In your model overload hasChildren(), canFetchMore() and fetchMore(). hasChildren() should return true for those index's that have children even if the rowCount() is currently 0. The default implementation will return true if rowCount() is greater then 0. QTreeView uses hasChildren() and not rowCount() to determine if it should draw the little triangle/plus symbol to expand that index. When the user clicks to expand the index QTreeView will call "if (canFetchMore(parent)) fetchMore(parent);" Taking advantage of this inside the model's fetchMore() implementation, the node can now be populated.

I have created a small example FtpModel which wraps QFtp. It will only list the directories that you have opened. It doesn't implement renaming, drag/drop, or any convenience for uploading/downloading files, but those can be added without much work if you want to take this and use it. Feel free to download the source and check out the model code. It is released under the BSD license.

On the right is a screenshot of the example application with a dirmodel on the left showing my home dir and on the right the ftp model connected back into my local box and a open directory.

No comments:

Popular Posts