Implementing QTreeView in QComboBox using Qt- Part 2

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

Introduction[edit | edit source]

This code demonstrates the QTreeView implemented in QComboBox. Here you can expand the tree view and also select the file you want, no restriction of QComboBox closing on one click, you can select items upto any level.

Name of classed used:

QTreeView-Provides a default model/view implementation of a tree view.

QDirModel-Provides a data model for the local file system.

Source Code[edit | edit source]

  1. include <QtGui/QApplication>
  2. include "widget.h"
  3. include<QComboBox>
  4. include<QDirModel>
  5. include<QTreeView>
  6. include<QEvent>
  7. include<QMouseEvent>
  8. include<QModelIndex>
  9. include<QDir>

class TreeBox : public QComboBox { public:

       TreeBox(QWidget* parent = 0) : QComboBox(parent), skipNextHide(false) //Widget creation
       {
               setView(new QTreeView(this));
               view()->viewport()->installEventFilter(this);
               QComboBox::resize(200,30);
       }
       bool eventFilter(QObject* object, QEvent* event)
       {
               if (event->type() == QEvent::MouseButtonPress && object == view()->viewport())
               {
                       QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event); 
                       QModelIndex index = view()->indexAt(mouseEvent->pos());
                       if (!view()->visualRect(index).contains(mouseEvent->pos()))
                               skipNextHide = true;
               }
               return false;
       }
       virtual void showPopup()
       {
               setRootModelIndex(static_cast<QDirModel*>(model())->index(QDir::rootPath()));
               QComboBox::showPopup();
       }
       virtual void hidePopup()
       {
               setRootModelIndex(view()->currentIndex().parent());
               setCurrentIndex(view()->currentIndex().row());
               if (skipNextHide)
                       skipNextHide = false;
               else
                       QComboBox::hidePopup();
       }

private:

       bool skipNextHide;

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

   QApplication a(argc, argv);
       TreeBox combo; //Class object declaration
       QDirModel model;
       combo.setModel(&model); //implemention QDir model
       combo.show();
   return a.exec();

}

Screenshot[edit | edit source]

File:Treecombo.JPG

Related Links[edit | edit source]

Implementing QTreeView in QComboBox using Qt- Part 1

pt:Archived:Implementando uma TreeView em um QComboBox - Parte 2
pt:Archived:Implementando uma TreeView em um QComboBox - Parte 2