How do I make a combobox look similar to the one used in file dialogs?

The differences with the combobox used in a file dialog is that it shows a hierarchical view and although this is possible by padding items with space you run into problems when you have icons as well as text as the icons are not padded.

To achieve this functionality then you can set a QTreeView [doc.qt.nokia.com] on the QComboBox [doc.qt.nokia.com] and with a tweak of some of the settings you can get it to resemble the combobox used on a QFileDialog [doc.qt.nokia.com].

The following is an example of how this can be done:

  1. #include <QtGui>
  2.  
  3. int main(int argc, char **argv)
  4. {
  5.     QApplication a(argc, argv);
  6.     QComboBox cb;
  7.     QTreeView *tv = new QTreeView;
  8.     tv->header()->hide();
  9.     QStandardItemModel *sim = new QStandardItemModel(1, 1);
  10.     QStandardItem *si = new QStandardItem;
  11.     QPixmap pix(16, 16);
  12.     pix.fill(Qt::red);
  13.     si->setText("C:\\");
  14.     si->setIcon(pix);
  15.     QStandardItem *childSi = new QStandardItem;
  16.     childSi->setText("windows");
  17.     pix.fill(Qt::blue);
  18.     childSi->setIcon(pix);
  19.     si->insertRow(0, childSi);
  20.     sim->setItem(0, 0, si);
  21.    
  22.     cb.setModel(sim);
  23.     cb.setModelColumn(0);
  24.     tv->setRootIsDecorated(false);
  25.     cb.setView(tv);
  26.     cb.show();
  27.     QTimer::singleShot(0, tv, SLOT(expandAll()));
  28.     return a.exec();
  29. }

NB: The call to QTimer::singleShot() is necessary as the expansion of the items needs to occur after the QComboBox and QTreeView are fully initalized after it gets shown.

No comments

Write a comment

Sorry, you must be logged in to post a comment.