PDA

View Full Version : [Snippet] QComboBox showing tree models



Auliyaa
25th November 2011, 14:42
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

#ifndef TREEVIEWCOMBOBOX_H
#define TREEVIEWCOMBOBOX_H

#include <QtGui/QComboBox>
#include <QtGui/QTreeView>

class TreeViewComboBox : public QComboBox {
Q_OBJECT
QTreeView* _treeView;
public:
explicit TreeViewComboBox(QWidget *parent = 0);
virtual void showPopup();

public slots:
void selectIndex(const QModelIndex&);
};
#endif // TREEVIEWCOMBOBOX_H

TreeViewComboBox.cpp

#include "TreeViewComboBox.h"

#include <QtGui/QHeaderView>

TreeViewComboBox::TreeViewComboBox(QWidget *parent): QComboBox(parent), _treeView(NULL) {
_treeView = new QTreeView(this);
_treeView->setFrameShape(QFrame::NoFrame);
_treeView->setEditTriggers(QTreeView::NoEditTriggers);
_treeView->setAlternatingRowColors(true);
_treeView->setSelectionBehavior(QTreeView::SelectRows);
_treeView->setRootIsDecorated(false);
_treeView->setWordWrap(true);
_treeView->setAllColumnsShowFocus(true);
_treeView->header()->setVisible(false);
setView(_treeView);
}

void TreeViewComboBox::showPopup() {
setRootModelIndex(QModelIndex());

for(int i=1;i<model()->columnCount();++i)
_treeView->hideColumn(i);

_treeView->expandAll();
_treeView->setItemsExpandable(false);
QComboBox::showPopup();
}

void TreeViewComboBox::selectIndex(const QModelIndex& index) {
setRootModelIndex(index.parent());
setCurrentIndex(index.row());
}


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.