Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.






(C++) Qt QTreeWidgetExample4


QTreeWidgetExample4 is an example of QTreeWidgetExample4.







Technical facts


Application type(s)

Operating system(s) or programming environment(s)


Project type:

C++ standard:


Libraries used:






Qt project file: CppQTreeWidgetExample4.pro


QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = CppQTreeWidgetExample4
SOURCES += main.cpp
FORMS    +=








#include <cassert>
#include <QApplication>
#include <QDebug>
#include <QDropEvent>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QDesktopWidget>

struct TwoLevelsDeepTree : public QTreeWidget
  void dropEvent(QDropEvent *event)
    //Process all items
    const int n_top = this->topLevelItemCount();
    for (int i=0; i!=n_top; ++i)
      QTreeWidgetItem * const top = this->topLevelItem(i);
      //Allow dropping on top-level items
        | Qt::ItemIsEnabled
        | Qt::ItemIsEditable
        | Qt::ItemIsDragEnabled
        | Qt::ItemIsDropEnabled);
      const int n_child = top->childCount();
      for (int j=0; j!=n_child; ++j)
        //Disallow dropping on non-top-level items
          | Qt::ItemIsEnabled
          | Qt::ItemIsEditable
          | Qt::ItemIsDragEnabled);
  ///Find out the depth of an item
  int GetDepth(const QTreeWidgetItem * const item)
    int depth = 0;
    const QTreeWidgetItem * copy = item->parent();
      copy = copy->parent();
    return depth;

int main(int argc, char *argv[])
  QApplication a(argc, argv);
  TwoLevelsDeepTree w;

  //Hide the header

  //Add ten regular items
  for (int i=0; i!=10; ++i)
    QTreeWidgetItem * const item = new QTreeWidgetItem;
    item->setText(0,"Item #" + QString::number(i+1));
    //Allow the item to be edited
    item->setFlags( item->flags() | Qt::ItemIsEditable);

  //Let the row colors alternate

  //Allow items to be drag and dropped inside of the widget

  //Let the drag and drop be animated


  //Put the QTreeWidget in the center of the screen at 25% of the screen its size
    const QRect screen = QApplication::desktop()->screenGeometry();
    w.setGeometry(0,0,screen.width() * 1 / 4 ,screen.height() * 1 / 2);
    w.move( screen.center() - w.rect().center() );
  return a.exec();






Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.


Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml