Hi everyone,

I run into some problems trying to display tree models in a QComboBox lately and I was not able to found a clean solution on Internet.
I finally managed to create a very simple class that is able to display the first column of some tree item model so I thought I could post it here so that it could be useful to someone ^^

Here's the code:

TreeViewComboBox.h
Qt Code:
  1. #ifndef TREEVIEWCOMBOBOX_H
  2. #define TREEVIEWCOMBOBOX_H
  3.  
  4. #include <QtGui/QComboBox>
  5. #include <QtGui/QTreeView>
  6.  
  7. class TreeViewComboBox : public QComboBox {
  8. Q_OBJECT
  9. QTreeView* _treeView;
  10. public:
  11. explicit TreeViewComboBox(QWidget *parent = 0);
  12. virtual void showPopup();
  13.  
  14. public slots:
  15. void selectIndex(const QModelIndex&);
  16. };
  17. #endif // TREEVIEWCOMBOBOX_H
To copy to clipboard, switch view to plain text mode 

TreeViewComboBox.cpp
Qt Code:
  1. #include "TreeViewComboBox.h"
  2.  
  3. #include <QtGui/QHeaderView>
  4.  
  5. TreeViewComboBox::TreeViewComboBox(QWidget *parent): QComboBox(parent), _treeView(NULL) {
  6. _treeView = new QTreeView(this);
  7. _treeView->setFrameShape(QFrame::NoFrame);
  8. _treeView->setEditTriggers(QTreeView::NoEditTriggers);
  9. _treeView->setAlternatingRowColors(true);
  10. _treeView->setSelectionBehavior(QTreeView::SelectRows);
  11. _treeView->setRootIsDecorated(false);
  12. _treeView->setWordWrap(true);
  13. _treeView->setAllColumnsShowFocus(true);
  14. _treeView->header()->setVisible(false);
  15. setView(_treeView);
  16. }
  17.  
  18. void TreeViewComboBox::showPopup() {
  19. setRootModelIndex(QModelIndex());
  20.  
  21. for(int i=1;i<model()->columnCount();++i)
  22. _treeView->hideColumn(i);
  23.  
  24. _treeView->expandAll();
  25. _treeView->setItemsExpandable(false);
  26. QComboBox::showPopup();
  27. }
  28.  
  29. void TreeViewComboBox::selectIndex(const QModelIndex& index) {
  30. setRootModelIndex(index.parent());
  31. setCurrentIndex(index.row());
  32. }
To copy to clipboard, switch view to plain text mode 

The code itself is pretty much self-explanatory and the tree view can be tweaked in various way.

Cheers

EDIT: Since QComboBox's currentIndex property supports only top-level indexes, you can use the selectIndex method to pre-select item from your code.