Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to Insert checkbox in root of Qtreeview. Treeview is created by using QDOMDocument reading XML file.

How to Insert checkbox in root of Qtreeview. Treeview is created by using QDOMDocument reading XML file.

Scheduled Pinned Locked Moved Unsolved General and Desktop
45 Posts 3 Posters 5.9k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Aviral 0
    wrote on 27 Nov 2022, 07:35 last edited by
    #1

    DomModel.cpp

    #include "DomModel.h"
    #include "DOMItem.h"
    #include "mainwindow.h"
    #include <QtXml>
    #include<QCheckBox>
    
    //! [0]
    DomModel::DomModel(const QDomDocument &document, QObject *parent)
        : QAbstractItemModel(parent),
          domDocument(document),
          rootItem(new DomItem(domDocument, 0))
    {
    }
    //! [0]
    
    //! [1]
    DomModel::~DomModel()
    {
        delete rootItem;
    }
    //! [1]
    
    //! [2]
    int DomModel::columnCount(const QModelIndex &parent) const
    {
        Q_UNUSED(parent);
        return 3;
    }
    //! [2]
    
    //! [3]
    QVariant DomModel::data(const QModelIndex &index, int role) const
    {
        if (!index.isValid())
            return QVariant();
    
        if (role != Qt::DisplayRole)
            return QVariant();
    
        const DomItem *item = static_cast<DomItem*>(index.internalPointer());
    
        const QDomNode node = item->node();
    //! [3] //! [4]
    
        switch (index.column()) {
            case 0:
                return node.nodeName();
            case 1:
            {
                const QDomNamedNodeMap attributeMap = node.attributes();
                QStringList attributes;
                for (int i = 0; i < attributeMap.count(); ++i) {
                    QDomNode attribute = attributeMap.item(i);
                    attributes << attribute.nodeName() + "=\""
                                  + attribute.nodeValue() + '"';
                }
                return attributes.join(' ');
            }
            case 2:
                return node.nodeValue().split('\n').join(' ');
            default:
                break;
        }
        return QVariant();
    }
    //! [4]
    
    //! [5]
    Qt::ItemFlags DomModel::flags(const QModelIndex &index) const
    {
        if (!index.isValid())
            return Qt::NoItemFlags;
    
        return QAbstractItemModel::flags(index);
    }
    //! [5]
    
    //! [6]
    QVariant DomModel::headerData(int section, Qt::Orientation orientation,
                                  int role) const
    {
        if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
            switch (section) {
                case 0:
                    return tr("Name");
                case 1:
                    return tr("Attributes");
                case 2:
                    return tr("Value");
                default:
                    break;
            }
        }
        return QVariant();
    }
    //! [6]
    
    //! [7]
    QModelIndex DomModel::index(int row, int column, const QModelIndex &parent) const
    {
        if (!hasIndex(row, column, parent))
            return QModelIndex();
    
        DomItem *parentItem;
    
        if (!parent.isValid())
            parentItem = rootItem;
        else
            parentItem = static_cast<DomItem*>(parent.internalPointer());
    //! [7]
    
    //! [8]
        DomItem *childItem = parentItem->child(row);
        if (childItem)
            return createIndex(row, column, childItem);
        return QModelIndex();
    }
    //! [8]
    
    //! [9]
    QModelIndex DomModel::parent(const QModelIndex &child) const
    {
        if (!child.isValid())
            return QModelIndex();
    
        DomItem *childItem = static_cast<DomItem*>(child.internalPointer());
        DomItem *parentItem = childItem->parent();
    
        if (!parentItem || parentItem == rootItem)
            return QModelIndex();
    
        return createIndex(parentItem->row(), 0, parentItem);
    }
    //! [9]
    
    //! [10]
    int DomModel::rowCount(const QModelIndex &parent) const
    {
        if (parent.column() > 0)
            return 0;
    
        DomItem *parentItem;
    
        if (!parent.isValid())
            parentItem = rootItem;
        else
            parentItem = static_cast<DomItem*>(parent.internalPointer());
    
        return parentItem->node().childNodes().count();
    }
    //! [10]
    

    DomItem.cpp

    #include "DOMItem.h"
    #include <QtXml>
    
    //! [0]
    DomItem::DomItem(const QDomNode &node, int row, DomItem *parent)
        : domNode(node),
    //! [0]
          // Record the item's location within its parent.
    //! [1]
          parentItem(parent),
          rowNumber(row)
    {}
    //! [1]
    
    //! [2]
    DomItem::~DomItem()
    {
        qDeleteAll(childItems);
    }
    //! [2]
    
    //! [3]
    QDomNode DomItem::node() const
    {
        return domNode;
    }
    //! [3]
    
    //! [4]
    DomItem *DomItem::parent()
    {
        return parentItem;
    }
    //! [4]
    
    //! [5]
    DomItem *DomItem::child(int i)
    {
        DomItem *childItem = childItems.value(i);
        if (childItem)
            return childItem;
    
        // if child does not yet exist, create it
        if (i >= 0 && i < domNode.childNodes().count()) {
            QDomNode childNode = domNode.childNodes().item(i);
            childItem = new DomItem(childNode, i, this);
            childItems[i] = childItem;
        }
        return childItem;
    }
    //! [5]
    
    //! [6]
    int DomItem::row() const
    {
        return rowNumber;
    }
    //! [6]
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    #include "DomModel.h"
    
    #include <QDomDocument>
    #include <QTreeView>
    #include <QMenuBar>
    #include <QFileDialog>
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent),
          model(new DomModel(QDomDocument(), this)),
          view(new QTreeView(this))
    {
        fileMenu = menuBar()->addMenu(tr("&File"));
        fileMenu->addAction(tr("&Open..."), this, &MainWindow::openFile, QKeySequence::Open);
        fileMenu->addAction(tr("E&xit"), this, &QWidget::close, QKeySequence::Quit);
    
        view->setModel(model);
    
        setCentralWidget(view);
        setWindowTitle(tr("QTreeViewXML"));
        setWindowIcon(QIcon("C:\\Users\arpit.k\\Documents\\QT\\build-QTreeViewXML-Desktop_Qt_6_2_4_MinGW_64_bit-Debug\\Accordlogo.png"));
    }
    
    void MainWindow::openFile()
    {
        QString filePath = QFileDialog::getOpenFileName(this, tr("Open File"),
            xmlPath, tr("XML files (*.xml);;HTML files (*.html);;"
                        "SVG files (*.svg);;User Interface files (*.ui)"));
    
        if (!filePath.isEmpty()) {
            QFile file(filePath);
            if (file.open(QIODevice::ReadOnly)) {
                QDomDocument document;
                if (document.setContent(&file)) {
                    DomModel *newModel = new DomModel(document, this);
                    view->setModel(newModel);
                    delete model;
                    model = newModel;
                    xmlPath = filePath;
                }
                file.close();
            }
        }
    }
    
    

    main.cpp

    #include "mainwindow.h"
    
    #include <QApplication>
    
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
        MainWindow window;
        window.resize(640, 480);
        window.show();
        return app.exec();
    }
    
    
    J 1 Reply Last reply 27 Nov 2022, 08:36
    0
    • A Aviral 0
      27 Nov 2022, 07:35

      DomModel.cpp

      #include "DomModel.h"
      #include "DOMItem.h"
      #include "mainwindow.h"
      #include <QtXml>
      #include<QCheckBox>
      
      //! [0]
      DomModel::DomModel(const QDomDocument &document, QObject *parent)
          : QAbstractItemModel(parent),
            domDocument(document),
            rootItem(new DomItem(domDocument, 0))
      {
      }
      //! [0]
      
      //! [1]
      DomModel::~DomModel()
      {
          delete rootItem;
      }
      //! [1]
      
      //! [2]
      int DomModel::columnCount(const QModelIndex &parent) const
      {
          Q_UNUSED(parent);
          return 3;
      }
      //! [2]
      
      //! [3]
      QVariant DomModel::data(const QModelIndex &index, int role) const
      {
          if (!index.isValid())
              return QVariant();
      
          if (role != Qt::DisplayRole)
              return QVariant();
      
          const DomItem *item = static_cast<DomItem*>(index.internalPointer());
      
          const QDomNode node = item->node();
      //! [3] //! [4]
      
          switch (index.column()) {
              case 0:
                  return node.nodeName();
              case 1:
              {
                  const QDomNamedNodeMap attributeMap = node.attributes();
                  QStringList attributes;
                  for (int i = 0; i < attributeMap.count(); ++i) {
                      QDomNode attribute = attributeMap.item(i);
                      attributes << attribute.nodeName() + "=\""
                                    + attribute.nodeValue() + '"';
                  }
                  return attributes.join(' ');
              }
              case 2:
                  return node.nodeValue().split('\n').join(' ');
              default:
                  break;
          }
          return QVariant();
      }
      //! [4]
      
      //! [5]
      Qt::ItemFlags DomModel::flags(const QModelIndex &index) const
      {
          if (!index.isValid())
              return Qt::NoItemFlags;
      
          return QAbstractItemModel::flags(index);
      }
      //! [5]
      
      //! [6]
      QVariant DomModel::headerData(int section, Qt::Orientation orientation,
                                    int role) const
      {
          if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
              switch (section) {
                  case 0:
                      return tr("Name");
                  case 1:
                      return tr("Attributes");
                  case 2:
                      return tr("Value");
                  default:
                      break;
              }
          }
          return QVariant();
      }
      //! [6]
      
      //! [7]
      QModelIndex DomModel::index(int row, int column, const QModelIndex &parent) const
      {
          if (!hasIndex(row, column, parent))
              return QModelIndex();
      
          DomItem *parentItem;
      
          if (!parent.isValid())
              parentItem = rootItem;
          else
              parentItem = static_cast<DomItem*>(parent.internalPointer());
      //! [7]
      
      //! [8]
          DomItem *childItem = parentItem->child(row);
          if (childItem)
              return createIndex(row, column, childItem);
          return QModelIndex();
      }
      //! [8]
      
      //! [9]
      QModelIndex DomModel::parent(const QModelIndex &child) const
      {
          if (!child.isValid())
              return QModelIndex();
      
          DomItem *childItem = static_cast<DomItem*>(child.internalPointer());
          DomItem *parentItem = childItem->parent();
      
          if (!parentItem || parentItem == rootItem)
              return QModelIndex();
      
          return createIndex(parentItem->row(), 0, parentItem);
      }
      //! [9]
      
      //! [10]
      int DomModel::rowCount(const QModelIndex &parent) const
      {
          if (parent.column() > 0)
              return 0;
      
          DomItem *parentItem;
      
          if (!parent.isValid())
              parentItem = rootItem;
          else
              parentItem = static_cast<DomItem*>(parent.internalPointer());
      
          return parentItem->node().childNodes().count();
      }
      //! [10]
      

      DomItem.cpp

      #include "DOMItem.h"
      #include <QtXml>
      
      //! [0]
      DomItem::DomItem(const QDomNode &node, int row, DomItem *parent)
          : domNode(node),
      //! [0]
            // Record the item's location within its parent.
      //! [1]
            parentItem(parent),
            rowNumber(row)
      {}
      //! [1]
      
      //! [2]
      DomItem::~DomItem()
      {
          qDeleteAll(childItems);
      }
      //! [2]
      
      //! [3]
      QDomNode DomItem::node() const
      {
          return domNode;
      }
      //! [3]
      
      //! [4]
      DomItem *DomItem::parent()
      {
          return parentItem;
      }
      //! [4]
      
      //! [5]
      DomItem *DomItem::child(int i)
      {
          DomItem *childItem = childItems.value(i);
          if (childItem)
              return childItem;
      
          // if child does not yet exist, create it
          if (i >= 0 && i < domNode.childNodes().count()) {
              QDomNode childNode = domNode.childNodes().item(i);
              childItem = new DomItem(childNode, i, this);
              childItems[i] = childItem;
          }
          return childItem;
      }
      //! [5]
      
      //! [6]
      int DomItem::row() const
      {
          return rowNumber;
      }
      //! [6]
      

      mainwindow.cpp

      #include "mainwindow.h"
      #include "ui_mainwindow.h"
      
      #include "DomModel.h"
      
      #include <QDomDocument>
      #include <QTreeView>
      #include <QMenuBar>
      #include <QFileDialog>
      
      MainWindow::MainWindow(QWidget *parent)
          : QMainWindow(parent),
            model(new DomModel(QDomDocument(), this)),
            view(new QTreeView(this))
      {
          fileMenu = menuBar()->addMenu(tr("&File"));
          fileMenu->addAction(tr("&Open..."), this, &MainWindow::openFile, QKeySequence::Open);
          fileMenu->addAction(tr("E&xit"), this, &QWidget::close, QKeySequence::Quit);
      
          view->setModel(model);
      
          setCentralWidget(view);
          setWindowTitle(tr("QTreeViewXML"));
          setWindowIcon(QIcon("C:\\Users\arpit.k\\Documents\\QT\\build-QTreeViewXML-Desktop_Qt_6_2_4_MinGW_64_bit-Debug\\Accordlogo.png"));
      }
      
      void MainWindow::openFile()
      {
          QString filePath = QFileDialog::getOpenFileName(this, tr("Open File"),
              xmlPath, tr("XML files (*.xml);;HTML files (*.html);;"
                          "SVG files (*.svg);;User Interface files (*.ui)"));
      
          if (!filePath.isEmpty()) {
              QFile file(filePath);
              if (file.open(QIODevice::ReadOnly)) {
                  QDomDocument document;
                  if (document.setContent(&file)) {
                      DomModel *newModel = new DomModel(document, this);
                      view->setModel(newModel);
                      delete model;
                      model = newModel;
                      xmlPath = filePath;
                  }
                  file.close();
              }
          }
      }
      
      

      main.cpp

      #include "mainwindow.h"
      
      #include <QApplication>
      
      
      int main(int argc, char *argv[])
      {
          QApplication app(argc, argv);
          MainWindow window;
          window.resize(640, 480);
          window.show();
          return app.exec();
      }
      
      
      J Offline
      J Offline
      JonB
      wrote on 27 Nov 2022, 08:36 last edited by JonB
      #2

      @Aviral-0
      Hello and welcome.

      Your first task is to change both your DomModel::data() & DomModel::flags() methods to support showing checkable items/checkboxes. The code in https://stackoverflow.com/a/8178567 shows how to do this. You need then to alter that to only return checkable/a checkbox for the root item, e.g. QModelIndex QAbstractItemView::rootIndex() const.

      A 2 Replies Last reply 27 Nov 2022, 11:05
      1
      • J JonB
        27 Nov 2022, 08:36

        @Aviral-0
        Hello and welcome.

        Your first task is to change both your DomModel::data() & DomModel::flags() methods to support showing checkable items/checkboxes. The code in https://stackoverflow.com/a/8178567 shows how to do this. You need then to alter that to only return checkable/a checkbox for the root item, e.g. QModelIndex QAbstractItemView::rootIndex() const.

        A Offline
        A Offline
        Aviral 0
        wrote on 27 Nov 2022, 11:05 last edited by
        #3

        @JonB Thankyou for your solution.
        Brother I am very new to coding and I don't think I can modify these code on my own, can you help me and Do this, I know its too much to ask and time consuming. I have to submit it tomorrow. Please brother help me! I would really appreciate your effort.

        1 Reply Last reply
        0
        • J JonB
          27 Nov 2022, 08:36

          @Aviral-0
          Hello and welcome.

          Your first task is to change both your DomModel::data() & DomModel::flags() methods to support showing checkable items/checkboxes. The code in https://stackoverflow.com/a/8178567 shows how to do this. You need then to alter that to only return checkable/a checkbox for the root item, e.g. QModelIndex QAbstractItemView::rootIndex() const.

          A Offline
          A Offline
          Aviral 0
          wrote on 28 Nov 2022, 03:32 last edited by
          #4

          @JonB I have modified
          QVariant TreeModel::data
          Qt::ItemFlags TreeModel::flags
          But now the Treeview is not showing any content text and checkboxes are also not checkable.

          J 1 Reply Last reply 28 Nov 2022, 07:48
          0
          • A Aviral 0
            28 Nov 2022, 03:32

            @JonB I have modified
            QVariant TreeModel::data
            Qt::ItemFlags TreeModel::flags
            But now the Treeview is not showing any content text and checkboxes are also not checkable.

            J Offline
            J Offline
            JonB
            wrote on 28 Nov 2022, 07:48 last edited by
            #5

            @Aviral-0
            Then that would depend on what code you have written....

            1 Reply Last reply
            1
            • A Offline
              A Offline
              Aviral 0
              wrote on 29 Nov 2022, 14:38 last edited by
              #6

              Hi, I have done this, still not able to make check boxes work and not able to make checkboxes at the root only.

              DomItem.cpp
              
              #include "DOMItem.h"
              #include<QCheckBox>
              #include <QtXml>
              
              //! [0]
              DomItem::DomItem(const QDomNode &node, int row, DomItem *parent)
                  : domNode(node),
              //! [0]
                    // Record the item's location within its parent.
              //! [1]
                    parentItem(parent),
                    rowNumber(row)
              {}
              //! [1]
              
              //! [2]
              DomItem::~DomItem()
              {
                  qDeleteAll(childItems);
              }
              //! [2]
              
              //! [3]
              QDomNode DomItem::node() const
              {
                  return domNode;
              }
              //! [3]
              
              //! [4]
              DomItem *DomItem::parent()
              {
                  return parentItem;
              }
              //! [4]
              
              //! [5]
              DomItem *DomItem::child(int i)
              {
                  DomItem *childItem = childItems.value(i);
                  if (childItem)
                      return childItem;
              
                  // if child does not yet exist, create it
                  if (i >= 0 && i < domNode.childNodes().count()) {
                      QDomNode childNode = domNode.childNodes().item(i);
                      childItem = new DomItem(childNode, i, this);
                      childItems[i] = childItem;
                  }
                  return childItem;
              }
              //! [5]
              
              //! [6]
              int DomItem::row() const
              {
                  return rowNumber;
              }
              //! [6]
              QVariant DomItem::data(int column) const
              {
                  return itemData.value(column);
              }
              
              
              
              DomModel.cpp
              
              #include "DomModel.h"
              #include "DOMItem.h"
              //#include "mainwindow.h"
              #include <QtXml>
              #include<QCheckBox>
              
              //! [0]
              DomModel::DomModel(const QDomDocument &document, QObject *parent)
                  : QAbstractItemModel(parent),
                    domDocument(document),
                    rootItem(new DomItem(domDocument, 0))
              {
              }
              //! [0]
              
              //! [1]
              DomModel::~DomModel()
              {
                  delete rootItem;
              }
              //! [1]
              
              //! [2]
              int DomModel::columnCount(const QModelIndex &parent) const
              {
                  Q_UNUSED(parent);
                  return 3;
              }
              //! [2]
              
              /*/! [3]
              QVariant DomModel::data(const QModelIndex &index, int role) const
              {
                  if (!index.isValid())
                      return QVariant();
              
                  if (role != Qt::DisplayRole)
                      return QVariant();
              
                  const DomItem *item = static_cast<DomItem*>(index.internalPointer());
              
                  const QDomNode node = item->node();
              //! [3] //! [4]
              
                  switch (index.column()) {
                      case 0:
                          return node.nodeName();
                      case 1:
                      {
                          const QDomNamedNodeMap attributeMap = node.attributes();
                          QStringList attributes;
                          for (int i = 0; i < attributeMap.count(); ++i) {
                              QDomNode attribute = attributeMap.item(i);
                              attributes << attribute.nodeName() + "=\""
                                            + attribute.nodeValue() + '"';
                          }
                          return attributes.join(' ');
                      }
                      case 2:
                          return node.nodeValue().split('\n').join(' ');
                      default:
                          break;
                  }
                  return QVariant();
              }
              //! [4] */
              
              QVariant DomModel::data(const QModelIndex &index, int role) const
              {
                  if (!index.isValid())
                      return QVariant();
              
                  DomItem *item = static_cast<DomItem*>(index.internalPointer());
                  const QDomNode node = item->node();
              
              
                  if ( role == Qt::CheckStateRole && index.column() == 0 )
                      return static_cast< int >( item->isChecked() ? Qt::Checked : Qt::Unchecked );
              
                  if (role != Qt::DisplayRole)
                      return QVariant();
              
                  switch (index.column()) {
                      case 0:
                          return node.nodeName();
                      case 1:
                      {
                          const QDomNamedNodeMap attributeMap = node.attributes();
                          QStringList attributes;
                          for (int i = 0; i < attributeMap.count(); ++i) {
                              QDomNode attribute = attributeMap.item(i);
                              attributes << attribute.nodeName() + "=\""
                                            + attribute.nodeValue() + '"';
                          }
                          return attributes.join(' ');
                      }
                      case 2:
                          return node.nodeValue().split('\n').join(' ');
                      default:
                          break;
                  }
                  return item->data(index.column());
              }
              
              /*
              //! [5]
              Qt::ItemFlags DomModel::flags(const QModelIndex &index) const
              {
                  if (!index.isValid())
                      return Qt::NoItemFlags;
              
                  return QAbstractItemModel::flags(index);
              }
              //! [5]
              */
              Qt::ItemFlags DomModel::flags(const QModelIndex &index) const
              {
                  if (!index.isValid())
                      return Qt::NoItemFlags;
              
                  Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
              
                  if ( index.column() == 0 )
                      flags |= Qt::ItemIsUserCheckable;
              
                  return flags;
              }
              //! [6]
              QVariant DomModel::headerData(int section, Qt::Orientation orientation,
                                            int role) const
              {
                  if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
                      switch (section) {
                          case 0:
                              return tr("Name");
                          case 1:
                              return tr("Attributes");
                          case 2:
                              return tr("Value");
                          default:
                              break;
                      }
                  }
                  return QVariant();
              }
              //! [6]
              
              //! [7]
              QModelIndex DomModel::index(int row, int column, const QModelIndex &parent) const
              {
                  if (!hasIndex(row, column, parent))
                      return QModelIndex();
              
                  DomItem *parentItem;
              
                  if (!parent.isValid())
                      parentItem = rootItem;
                  else
                      parentItem = static_cast<DomItem*>(parent.internalPointer());
              //! [7]
              
              //! [8]
                  DomItem *childItem = parentItem->child(row);
                  if (childItem)
                      return createIndex(row, column, childItem);
                  return QModelIndex();
              }
              //! [8]
              
              //! [9]
              QModelIndex DomModel::parent(const QModelIndex &child) const
              {
                  if (!child.isValid())
                      return QModelIndex();
              
                  DomItem *childItem = static_cast<DomItem*>(child.internalPointer());
                  DomItem *parentItem = childItem->parent();
              
                  if (!parentItem || parentItem == rootItem)
                      return QModelIndex();
              
                  return createIndex(parentItem->row(), 0, parentItem);
              }
              //! [9]
              
              //! [10]
              int DomModel::rowCount(const QModelIndex &parent) const
              {
                  if (parent.column() > 0)
                      return 0;
              
                  DomItem *parentItem;
              
                  if (!parent.isValid())
                      parentItem = rootItem;
                  else
                      parentItem = static_cast<DomItem*>(parent.internalPointer());
              
                  return parentItem->node().childNodes().count();
              }
              //! [10]
              
              
              mainwindow.cpp
              
              #include "mainwindow.h"
              #include "ui_mainwindow.h"
              
              #include "DomModel.h"
              
              #include <QDomDocument>
              #include <QTreeView>
              #include <QMenuBar>
              #include <QFileDialog>
              
              MainWindow::MainWindow(QWidget *parent)
                  : QMainWindow(parent),
                    model(new DomModel(QDomDocument(), this)),
                    view(new QTreeView(this))
              {
                  fileMenu = menuBar()->addMenu(tr("&File"));
                  fileMenu->addAction(tr("&Open..."), this, &MainWindow::openFile, QKeySequence::Open);
                  fileMenu->addAction(tr("E&xit"), this, &QWidget::close, QKeySequence::Quit);
              
                  view->setModel(model);
              
                  setCentralWidget(view);
                  setWindowTitle(tr("QTreeViewXML"));
                  setWindowIcon(QIcon("C:\\Users\arpit.k\\Documents\\QT\\build-QTreeViewXML-Desktop_Qt_6_2_4_MinGW_64_bit-Debug\\Accordlogo.png"));
              }
              
              void MainWindow::openFile()
              {
                  QString filePath = QFileDialog::getOpenFileName(this, tr("Open File"),
                      xmlPath, tr("XML files (*.xml);;HTML files (*.html);;"
                                  "SVG files (*.svg);;User Interface files (*.ui)"));
              
                  if (!filePath.isEmpty()) {
                      QFile file(filePath);
                      if (file.open(QIODevice::ReadOnly)) {
                          QDomDocument document;
                          if (document.setContent(&file)) {
                              DomModel *newModel = new DomModel(document, this);
                              view->setModel(newModel);
                              delete model;
                              model = newModel;
                              xmlPath = filePath;
                          }
                          file.close();
                      }
                  }
              }
              
              

              Please help!

              J 1 Reply Last reply 29 Nov 2022, 14:55
              0
              • A Aviral 0
                29 Nov 2022, 14:38

                Hi, I have done this, still not able to make check boxes work and not able to make checkboxes at the root only.

                DomItem.cpp
                
                #include "DOMItem.h"
                #include<QCheckBox>
                #include <QtXml>
                
                //! [0]
                DomItem::DomItem(const QDomNode &node, int row, DomItem *parent)
                    : domNode(node),
                //! [0]
                      // Record the item's location within its parent.
                //! [1]
                      parentItem(parent),
                      rowNumber(row)
                {}
                //! [1]
                
                //! [2]
                DomItem::~DomItem()
                {
                    qDeleteAll(childItems);
                }
                //! [2]
                
                //! [3]
                QDomNode DomItem::node() const
                {
                    return domNode;
                }
                //! [3]
                
                //! [4]
                DomItem *DomItem::parent()
                {
                    return parentItem;
                }
                //! [4]
                
                //! [5]
                DomItem *DomItem::child(int i)
                {
                    DomItem *childItem = childItems.value(i);
                    if (childItem)
                        return childItem;
                
                    // if child does not yet exist, create it
                    if (i >= 0 && i < domNode.childNodes().count()) {
                        QDomNode childNode = domNode.childNodes().item(i);
                        childItem = new DomItem(childNode, i, this);
                        childItems[i] = childItem;
                    }
                    return childItem;
                }
                //! [5]
                
                //! [6]
                int DomItem::row() const
                {
                    return rowNumber;
                }
                //! [6]
                QVariant DomItem::data(int column) const
                {
                    return itemData.value(column);
                }
                
                
                
                DomModel.cpp
                
                #include "DomModel.h"
                #include "DOMItem.h"
                //#include "mainwindow.h"
                #include <QtXml>
                #include<QCheckBox>
                
                //! [0]
                DomModel::DomModel(const QDomDocument &document, QObject *parent)
                    : QAbstractItemModel(parent),
                      domDocument(document),
                      rootItem(new DomItem(domDocument, 0))
                {
                }
                //! [0]
                
                //! [1]
                DomModel::~DomModel()
                {
                    delete rootItem;
                }
                //! [1]
                
                //! [2]
                int DomModel::columnCount(const QModelIndex &parent) const
                {
                    Q_UNUSED(parent);
                    return 3;
                }
                //! [2]
                
                /*/! [3]
                QVariant DomModel::data(const QModelIndex &index, int role) const
                {
                    if (!index.isValid())
                        return QVariant();
                
                    if (role != Qt::DisplayRole)
                        return QVariant();
                
                    const DomItem *item = static_cast<DomItem*>(index.internalPointer());
                
                    const QDomNode node = item->node();
                //! [3] //! [4]
                
                    switch (index.column()) {
                        case 0:
                            return node.nodeName();
                        case 1:
                        {
                            const QDomNamedNodeMap attributeMap = node.attributes();
                            QStringList attributes;
                            for (int i = 0; i < attributeMap.count(); ++i) {
                                QDomNode attribute = attributeMap.item(i);
                                attributes << attribute.nodeName() + "=\""
                                              + attribute.nodeValue() + '"';
                            }
                            return attributes.join(' ');
                        }
                        case 2:
                            return node.nodeValue().split('\n').join(' ');
                        default:
                            break;
                    }
                    return QVariant();
                }
                //! [4] */
                
                QVariant DomModel::data(const QModelIndex &index, int role) const
                {
                    if (!index.isValid())
                        return QVariant();
                
                    DomItem *item = static_cast<DomItem*>(index.internalPointer());
                    const QDomNode node = item->node();
                
                
                    if ( role == Qt::CheckStateRole && index.column() == 0 )
                        return static_cast< int >( item->isChecked() ? Qt::Checked : Qt::Unchecked );
                
                    if (role != Qt::DisplayRole)
                        return QVariant();
                
                    switch (index.column()) {
                        case 0:
                            return node.nodeName();
                        case 1:
                        {
                            const QDomNamedNodeMap attributeMap = node.attributes();
                            QStringList attributes;
                            for (int i = 0; i < attributeMap.count(); ++i) {
                                QDomNode attribute = attributeMap.item(i);
                                attributes << attribute.nodeName() + "=\""
                                              + attribute.nodeValue() + '"';
                            }
                            return attributes.join(' ');
                        }
                        case 2:
                            return node.nodeValue().split('\n').join(' ');
                        default:
                            break;
                    }
                    return item->data(index.column());
                }
                
                /*
                //! [5]
                Qt::ItemFlags DomModel::flags(const QModelIndex &index) const
                {
                    if (!index.isValid())
                        return Qt::NoItemFlags;
                
                    return QAbstractItemModel::flags(index);
                }
                //! [5]
                */
                Qt::ItemFlags DomModel::flags(const QModelIndex &index) const
                {
                    if (!index.isValid())
                        return Qt::NoItemFlags;
                
                    Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
                
                    if ( index.column() == 0 )
                        flags |= Qt::ItemIsUserCheckable;
                
                    return flags;
                }
                //! [6]
                QVariant DomModel::headerData(int section, Qt::Orientation orientation,
                                              int role) const
                {
                    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
                        switch (section) {
                            case 0:
                                return tr("Name");
                            case 1:
                                return tr("Attributes");
                            case 2:
                                return tr("Value");
                            default:
                                break;
                        }
                    }
                    return QVariant();
                }
                //! [6]
                
                //! [7]
                QModelIndex DomModel::index(int row, int column, const QModelIndex &parent) const
                {
                    if (!hasIndex(row, column, parent))
                        return QModelIndex();
                
                    DomItem *parentItem;
                
                    if (!parent.isValid())
                        parentItem = rootItem;
                    else
                        parentItem = static_cast<DomItem*>(parent.internalPointer());
                //! [7]
                
                //! [8]
                    DomItem *childItem = parentItem->child(row);
                    if (childItem)
                        return createIndex(row, column, childItem);
                    return QModelIndex();
                }
                //! [8]
                
                //! [9]
                QModelIndex DomModel::parent(const QModelIndex &child) const
                {
                    if (!child.isValid())
                        return QModelIndex();
                
                    DomItem *childItem = static_cast<DomItem*>(child.internalPointer());
                    DomItem *parentItem = childItem->parent();
                
                    if (!parentItem || parentItem == rootItem)
                        return QModelIndex();
                
                    return createIndex(parentItem->row(), 0, parentItem);
                }
                //! [9]
                
                //! [10]
                int DomModel::rowCount(const QModelIndex &parent) const
                {
                    if (parent.column() > 0)
                        return 0;
                
                    DomItem *parentItem;
                
                    if (!parent.isValid())
                        parentItem = rootItem;
                    else
                        parentItem = static_cast<DomItem*>(parent.internalPointer());
                
                    return parentItem->node().childNodes().count();
                }
                //! [10]
                
                
                mainwindow.cpp
                
                #include "mainwindow.h"
                #include "ui_mainwindow.h"
                
                #include "DomModel.h"
                
                #include <QDomDocument>
                #include <QTreeView>
                #include <QMenuBar>
                #include <QFileDialog>
                
                MainWindow::MainWindow(QWidget *parent)
                    : QMainWindow(parent),
                      model(new DomModel(QDomDocument(), this)),
                      view(new QTreeView(this))
                {
                    fileMenu = menuBar()->addMenu(tr("&File"));
                    fileMenu->addAction(tr("&Open..."), this, &MainWindow::openFile, QKeySequence::Open);
                    fileMenu->addAction(tr("E&xit"), this, &QWidget::close, QKeySequence::Quit);
                
                    view->setModel(model);
                
                    setCentralWidget(view);
                    setWindowTitle(tr("QTreeViewXML"));
                    setWindowIcon(QIcon("C:\\Users\arpit.k\\Documents\\QT\\build-QTreeViewXML-Desktop_Qt_6_2_4_MinGW_64_bit-Debug\\Accordlogo.png"));
                }
                
                void MainWindow::openFile()
                {
                    QString filePath = QFileDialog::getOpenFileName(this, tr("Open File"),
                        xmlPath, tr("XML files (*.xml);;HTML files (*.html);;"
                                    "SVG files (*.svg);;User Interface files (*.ui)"));
                
                    if (!filePath.isEmpty()) {
                        QFile file(filePath);
                        if (file.open(QIODevice::ReadOnly)) {
                            QDomDocument document;
                            if (document.setContent(&file)) {
                                DomModel *newModel = new DomModel(document, this);
                                view->setModel(newModel);
                                delete model;
                                model = newModel;
                                xmlPath = filePath;
                            }
                            file.close();
                        }
                    }
                }
                
                

                Please help!

                J Offline
                J Offline
                JonB
                wrote on 29 Nov 2022, 14:55 last edited by JonB
                #7

                @Aviral-0 said in How to Insert checkbox in root of Qtreeview. Treeview is created by using QDOMDocument reading XML file.:

                still not able to make check boxes work

                What exactly does this mean? Do you get to see any checkboxes? You do but they are not checkable? Or what?

                make checkboxes at the root only.

                I do not see anything in your data() method, CheckStateRole case, which attempts to only return the checked state for the root item, rather than for all/any item. I suggested you look at QAbstractItemView::rootIndex(), but I don't see that or any equivalent code.

                A 1 Reply Last reply 29 Nov 2022, 16:02
                1
                • J JonB
                  29 Nov 2022, 14:55

                  @Aviral-0 said in How to Insert checkbox in root of Qtreeview. Treeview is created by using QDOMDocument reading XML file.:

                  still not able to make check boxes work

                  What exactly does this mean? Do you get to see any checkboxes? You do but they are not checkable? Or what?

                  make checkboxes at the root only.

                  I do not see anything in your data() method, CheckStateRole case, which attempts to only return the checked state for the root item, rather than for all/any item. I suggested you look at QAbstractItemView::rootIndex(), but I don't see that or any equivalent code.

                  A Offline
                  A Offline
                  Aviral 0
                  wrote on 29 Nov 2022, 16:02 last edited by
                  #8

                  @JonB Yes, the checkbox appeared but not working as check or unchecked.

                  J 1 Reply Last reply 29 Nov 2022, 16:14
                  0
                  • A Aviral 0
                    29 Nov 2022, 16:02

                    @JonB Yes, the checkbox appeared but not working as check or unchecked.

                    J Offline
                    J Offline
                    JonB
                    wrote on 29 Nov 2022, 16:14 last edited by
                    #9

                    @Aviral-0
                    Your DomModel::data() method has correct code to look at item->isChecked() to see whether to show checked/unchecked. But I do not see anywhere in your code which sets any DomItem (or its QDomNode returned by node()) to record that it has been checked. You have to store that somewhere. And if DomModel::data() looks at item->isChecked() for CheckStateRole I think I would expect you to have a corresponding setData() with case for CheckStateRole which calls an item->setChecked().

                    A 1 Reply Last reply 29 Nov 2022, 16:38
                    1
                    • J JonB
                      29 Nov 2022, 16:14

                      @Aviral-0
                      Your DomModel::data() method has correct code to look at item->isChecked() to see whether to show checked/unchecked. But I do not see anywhere in your code which sets any DomItem (or its QDomNode returned by node()) to record that it has been checked. You have to store that somewhere. And if DomModel::data() looks at item->isChecked() for CheckStateRole I think I would expect you to have a corresponding setData() with case for CheckStateRole which calls an item->setChecked().

                      A Offline
                      A Offline
                      Aviral 0
                      wrote on 29 Nov 2022, 16:38 last edited by
                      #10

                      @JonB Thankyou, using setData() method the items are now checkable.
                      Just one thing I am not understanding. you said about
                      QModelIndex QAbstractItemView::rootIndex() const
                      I am not able to understand how to use it and where to use it.
                      as on website its not indepth elaboration about it.

                      J 1 Reply Last reply 29 Nov 2022, 17:44
                      0
                      • A Aviral 0
                        29 Nov 2022, 16:38

                        @JonB Thankyou, using setData() method the items are now checkable.
                        Just one thing I am not understanding. you said about
                        QModelIndex QAbstractItemView::rootIndex() const
                        I am not able to understand how to use it and where to use it.
                        as on website its not indepth elaboration about it.

                        J Offline
                        J Offline
                        JonB
                        wrote on 29 Nov 2022, 17:44 last edited by JonB
                        #11

                        @Aviral-0

                        Qt::ItemFlags DomModel::flags(const QModelIndex &index) const
                        {
                            if ( index.column() == 0 )
                                flags |= Qt::ItemIsUserCheckable;
                        

                        You said, I believe, that you only want a checkbox if it is the root index. You want to know whether index is the root index here. I realize now that QModelIndex QAbstractItemView::rootIndex() const is a method of the QTreeView and not available in model flags code. Is the root index row 0 in the model (I don't know)? So you would need maybe && index.row() == 0?

                        A 1 Reply Last reply 29 Nov 2022, 18:04
                        1
                        • J JonB
                          29 Nov 2022, 17:44

                          @Aviral-0

                          Qt::ItemFlags DomModel::flags(const QModelIndex &index) const
                          {
                              if ( index.column() == 0 )
                                  flags |= Qt::ItemIsUserCheckable;
                          

                          You said, I believe, that you only want a checkbox if it is the root index. You want to know whether index is the root index here. I realize now that QModelIndex QAbstractItemView::rootIndex() const is a method of the QTreeView and not available in model flags code. Is the root index row 0 in the model (I don't know)? So you would need maybe && index.row() == 0?

                          A Offline
                          A Offline
                          Aviral 0
                          wrote on 29 Nov 2022, 18:04 last edited by
                          #12

                          @JonB Using
                          && index.row() == 0
                          also didn't worked. I think index contains the current item location in tree

                          J 1 Reply Last reply 29 Nov 2022, 18:09
                          0
                          • A Aviral 0
                            29 Nov 2022, 18:04

                            @JonB Using
                            && index.row() == 0
                            also didn't worked. I think index contains the current item location in tree

                            J Offline
                            J Offline
                            JonB
                            wrote on 29 Nov 2022, 18:09 last edited by
                            #13

                            @Aviral-0
                            Your QTreeView has a root index, the one you want a checkbox against, right? How did that get set? You want to know that index in the model code so that you can check for it your data() code, right?

                            A 2 Replies Last reply 29 Nov 2022, 18:14
                            1
                            • J JonB
                              29 Nov 2022, 18:09

                              @Aviral-0
                              Your QTreeView has a root index, the one you want a checkbox against, right? How did that get set? You want to know that index in the model code so that you can check for it your data() code, right?

                              A Offline
                              A Offline
                              Aviral 0
                              wrote on 29 Nov 2022, 18:14 last edited by
                              #14

                              @JonB Sorry Jon, I really didn't understand. I am very new to coding.
                              In simple terms, yes I need checkbox only at root node.
                              Should I send you my updated code?

                              1 Reply Last reply
                              0
                              • J JonB
                                29 Nov 2022, 18:09

                                @Aviral-0
                                Your QTreeView has a root index, the one you want a checkbox against, right? How did that get set? You want to know that index in the model code so that you can check for it your data() code, right?

                                A Offline
                                A Offline
                                Aviral 0
                                wrote on 29 Nov 2022, 18:25 last edited by
                                #15

                                @JonB Please have a look at it.
                                https://github.com/aviralarpit/QTDomDoc.git

                                J 1 Reply Last reply 29 Nov 2022, 18:37
                                0
                                • A Aviral 0
                                  29 Nov 2022, 18:25

                                  @JonB Please have a look at it.
                                  https://github.com/aviralarpit/QTDomDoc.git

                                  J Offline
                                  J Offline
                                  JonB
                                  wrote on 29 Nov 2022, 18:37 last edited by
                                  #16

                                  @Aviral-0
                                  class DomModel has QModelIndex rootIndex() const; (though can't see an implementation?) or DomItem *rootItem you can use to identify the root item.

                                  A 2 Replies Last reply 29 Nov 2022, 18:39
                                  1
                                  • J JonB
                                    29 Nov 2022, 18:37

                                    @Aviral-0
                                    class DomModel has QModelIndex rootIndex() const; (though can't see an implementation?) or DomItem *rootItem you can use to identify the root item.

                                    A Offline
                                    A Offline
                                    Aviral 0
                                    wrote on 29 Nov 2022, 18:39 last edited by
                                    #17

                                    @JonB I tried to use rootIndex() function but didn't understood how to.
                                    Its just declaration.

                                    J 1 Reply Last reply 29 Nov 2022, 18:44
                                    0
                                    • A Aviral 0
                                      29 Nov 2022, 18:39

                                      @JonB I tried to use rootIndex() function but didn't understood how to.
                                      Its just declaration.

                                      J Offline
                                      J Offline
                                      JonB
                                      wrote on 29 Nov 2022, 18:44 last edited by JonB
                                      #18

                                      @Aviral-0 Which is what I thought and why I suggested you try recognising if the item is the rootItem.

                                      1 Reply Last reply
                                      0
                                      • J JonB
                                        29 Nov 2022, 18:37

                                        @Aviral-0
                                        class DomModel has QModelIndex rootIndex() const; (though can't see an implementation?) or DomItem *rootItem you can use to identify the root item.

                                        A Offline
                                        A Offline
                                        Aviral 0
                                        wrote on 29 Nov 2022, 18:50 last edited by
                                        #19

                                        @JonB I know its alot to ask, but can you tell me what change should I do specifically to make it work. It will be so nice of you taking your time to help me. Thankyou Brother.

                                        J 1 Reply Last reply 29 Nov 2022, 18:56
                                        0
                                        • A Aviral 0
                                          29 Nov 2022, 18:50

                                          @JonB I know its alot to ask, but can you tell me what change should I do specifically to make it work. It will be so nice of you taking your time to help me. Thankyou Brother.

                                          J Offline
                                          J Offline
                                          JonB
                                          wrote on 29 Nov 2022, 18:56 last edited by
                                          #20

                                          @Aviral-0
                                          I'm not your Brother!

                                          I think you want in flags():

                                              DomItem *item = static_cast<DomItem*>(index.internalPointer());
                                              if (item == rootItem)
                                                  flags |= Qt::ItemIsUserCheckable;
                                          

                                          to make it so only the root item is checkable.

                                          A 3 Replies Last reply 29 Nov 2022, 19:16
                                          1

                                          7/45

                                          29 Nov 2022, 14:55

                                          topic:navigator.unread, 38
                                          • Login

                                          • Login or register to search.
                                          7 out of 45
                                          • First post
                                            7/45
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved