Checkable Treeview not support for check and uncheck



  • I have developed a checkable tree view with help of some Qt examples.
    The program showing a checkable treeview as output.But unfortunately, it is not supporting for check and uncheck the items.
    How can i update the code for item should be possible to check and uncheck ??
    I am giving the class details below,

    Treeitem.h

    #ifndef TREEITEM_H
    #define TREEITEM_H
    
    #include <QList>
    
    #include <QVariant>
    
    
    
    
     class TreeItem
    
     {
    
    public:
    
    explicit TreeItem(const QList<QVariant> &data, TreeItem *parentItem = 0);
    
    ~TreeItem();
    
    void appendChild(TreeItem *child);
    TreeItem *child(int row);
    int childCount() const;
    int columnCount() const;
    QVariant data(int column) const;
    int row() const;
    TreeItem *parentItem();
    
    bool isChecked() const { return checked; }
    void setChecked( bool set ) { checked = set; }
    
    
    private:
     QList<TreeItem*> m_childItems;
     QList<QVariant> m_itemData;
     TreeItem *m_parentItem;
     bool checked;
     };
    
    
    #endif // TREEITEM_H
    

    TreeItem.cpp

    #include <QStringList>
    #include "treeitem.h"
    TreeItem::TreeItem(const QList<QVariant> &data, TreeItem *parent)
     {
      m_parentItem = parent;
      m_itemData = data;
      }
     TreeItem::~TreeItem()
     {
     qDeleteAll(m_childItems);
     }
     void TreeItem::appendChild(TreeItem *item)
    {
    m_childItems.append(item);
    }
    TreeItem *TreeItem::child(int row)
    {
    return m_childItems.value(row);
    }
    int TreeItem::childCount() const
    {
    return m_childItems.count();
    }
    int TreeItem::columnCount() const
    {
    return m_itemData.count();
    }
    QVariant TreeItem::data(int column) const
    {
    return m_itemData.value(column);
    }
    TreeItem *TreeItem::parentItem()
     {
     return m_parentItem;
     }
    int TreeItem::row() const
    {
      if (m_parentItem)
        return m_parentItem->m_childItems.indexOf(const_cast<TreeItem*>(this));
    
    return 0;
    }
    

    TrreeModel.h

    #ifndef TREEMODEL_H
    #define TREEMODEL_H
    
    #include <QAbstractItemModel>
    #include <QModelIndex>
    #include <QVariant>
    
    class TreeItem;
    
    //! [0]
    class TreeModel : public QAbstractItemModel
    {
        Q_OBJECT
    
    public:
        explicit TreeModel(const QString &data, QObject *parent = 0);
        ~TreeModel();
    
        QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
        Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE;
        QVariant headerData(int section, Qt::Orientation orientation,
                            int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
        QModelIndex index(int row, int column,
                          const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
        QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE;
        int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
        int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
    
    private:
        void setupModelData(const QStringList &lines, TreeItem *parent);
    
        TreeItem *rootItem;
    };
    //! [0]
    
    #endif // TREEMODEL_H
    

    TreeModel.cpp

    #include "treeitem.h"
    #include "treemodel.h"
    
    #include <QStringList>
    
    //! [0]
    TreeModel::TreeModel(const QString &data, QObject *parent)
        : QAbstractItemModel(parent)
    {
        QList<QVariant> rootData;
        rootData << "Title";
        rootItem = new TreeItem(rootData);
        setupModelData(data.split(QString("\n")), rootItem);
    }
    //! [0]
    
    //! [1]
    TreeModel::~TreeModel()
    {
        delete rootItem;
    }
    //! [1]
    
    //! [2]
    int TreeModel::columnCount(const QModelIndex &parent) const
    {
        if (parent.isValid())
            return static_cast<TreeItem*>(parent.internalPointer())->columnCount();
        else
            return rootItem->columnCount();
    }
    //! [2]
    
    //! [3]
    
    QVariant TreeModel::data(const QModelIndex &index, int role) const
    {
        if (!index.isValid())
            return QVariant();
    
        TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
    
        if ( role == Qt::CheckStateRole && index.column() == 0 )
            return static_cast< int >( item->isChecked() ? Qt::Checked : Qt::Unchecked );
    
        if (role != Qt::DisplayRole)
            return QVariant();
    
        return item->data(index.column());
    }
    
    //! [3]
    
    //! [4]
    
    Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
    {
        if (!index.isValid())
            return 0;
    
        Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable |Qt::ItemIsUserCheckable|Qt::ItemIsEditable;
    
        if ( index.column() == 0 )
            flags |= Qt::ItemIsUserCheckable;
    
        return flags;
    }
    //! [4]
    
    //! [5]
    QVariant TreeModel::headerData(int section, Qt::Orientation orientation,
                                   int role) const
    {
        if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
            return rootItem->data(section);
    
        return QVariant();
    }
    //! [5]
    
    //! [6]
    QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent)
                const
    {
        if (!hasIndex(row, column, parent))
            return QModelIndex();
    
        TreeItem *parentItem;
    
        if (!parent.isValid())
            parentItem = rootItem;
        else
            parentItem = static_cast<TreeItem*>(parent.internalPointer());
    
        TreeItem *childItem = parentItem->child(row);
        if (childItem)
            return createIndex(row, column, childItem);
        else
            return QModelIndex();
    }
    //! [6]
    
    //! [7]
    QModelIndex TreeModel::parent(const QModelIndex &index) const
    {
        if (!index.isValid())
            return QModelIndex();
    
        TreeItem *childItem = static_cast<TreeItem*>(index.internalPointer());
        TreeItem *parentItem = childItem->parentItem();
    
        if (parentItem == rootItem)
            return QModelIndex();
    
        return createIndex(parentItem->row(), 0, parentItem);
    }
    //! [7]
    
    //! [8]
    int TreeModel::rowCount(const QModelIndex &parent) const
    {
        TreeItem *parentItem;
        if (parent.column() > 0)
            return 0;
    
        if (!parent.isValid())
            parentItem = rootItem;
        else
            parentItem = static_cast<TreeItem*>(parent.internalPointer());
    
        return parentItem->childCount();
    }
    //! [8]
    
    void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent)
    {
        QList<TreeItem*> parents;
        QList<int> indentations;
        parents << parent;
        indentations << 0;
    
        int number = 0;
    
        while (number < lines.count()) {
            int position = 0;
            while (position < lines[number].length()) {
                if (lines[number].at(position) != ' ')
                    break;
                position++;
            }
    
            QString lineData = lines[number].mid(position).trimmed();
    
            if (!lineData.isEmpty()) {
                // Read the column data from the rest of the line.
                QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
                QList<QVariant> columnData;
                for (int column = 0; column < columnStrings.count(); ++column)
                    columnData << columnStrings[column];
    
                if (position > indentations.last()) {
                    // The last child of the current parent is now the new parent
                    // unless the current parent has no children.
    
                    if (parents.last()->childCount() > 0) {
                        parents << parents.last()->child(parents.last()->childCount()-1);
                        indentations << position;
                    }
                } else {
                    while (position < indentations.last() && parents.count() > 0) {
                        parents.pop_back();
                        indentations.pop_back();
                    }
                }
    
                // Append a new item to the current parent's list of children.
                parents.last()->appendChild(new TreeItem(columnData, parents.last()));
            }
    
            ++number;
        }
    }
    

    main.cpp

    #include "treemodel.h"
    
    #include <QApplication>
    #include <QFile>
    #include <QTreeView>
    
    #include <QTreeWidget>
    
    int main(int argc, char *argv[])
    {
        Q_INIT_RESOURCE(simpletreemodel);
    
        QApplication app(argc, argv);
    
    
    
    
        QFile file(":/default.txt");
        file.open(QIODevice::ReadOnly);
        TreeModel model(file.readAll());
        file.close();
    
        QTreeView view;
        view.setModel(&model);
    
        view.setWindowTitle(QObject::tr("Simple Tree Model"));
        view.show();
        return app.exec();
    }
    

    default.txt

    Brain Trauma
        T2			
        T3 Flair		
    
    Brain Tumour			
        Creating a Dialog			
        Composing the Dialog
    

    Output

    0_1497505860752_upload-9ef7b584-ef72-4eab-9327-d3e57bef4c0b



  • Could you try replacing your model with a default one and see if it works?
    In 90% of the cases you do not need to implement your own model, QStandardItemModel works well enough and you don't risk to forget something in your implementation (trust me, getting something wrong in a custom model is very easy). in addition, the QAbstractItemModel interface lets you change the model by just changing 1 line in case, in the future, you realise you really positively need a custom model.



  • @VRonin I have done it with help of QStandardItemModel and QStandardItem.
    SO presently checked qtreeview is developed.
    But how can get the selected items. If i select a parent then i should have the all index of its child how can i get ?



  • QObject::connect(model,&QAbstractItemModel::dataChanged,[model](const QModelIndex& idx)->void{
    if(!idx.isValid())
    return;
    Q_ASSERT(idx.model()==model);
    const QVariant newCheck = idx.data(Qt::CheckStateRole);
    if(newCheck ==idx.data(Qt::UserRole + Qt::CheckStateRole))
    return;
    model->setData(idx,newCheck ,Qt::UserRole + Qt::CheckStateRole);
    const int numRows = model->rowCount(idx);
    for(int i=0;i<numRows ;++i)
    model->setData(model->index(i,idx.column(),idx),newCheck,Qt::CheckStateRole);
    });
    
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.