Search code examples
c++qtobjectqtreeviewqstandarditem

what is the proper way to keep track objects on a QTreeView/QStandardItem


I have a QTreeView that has three branches under a rootnode

QTreeView treeView_4 = new QTreeView(tab_10);
QStandardItemModel standardModel = new QStandardItemModel ;
QStandardItem *rootNode = standardModel->invisibleRootItem();

QStandardItem Group1Item =  new QStandardItem("Group 1");
QStandardItem Group2Item =  new QStandardItem("Group 2");
QStandardItem Group3Item =  new QStandardItem("Group 3");

rootNode->appendRow(Group1Item);
rootNode->appendRow(Group2Item);
rootNode->appendRow(Group3Item);

I want to list some objects under Group1/2/3 when they are created. When a property of an Object changes, I want to move them from one group to another (like some status change). An object have two properties that is interesting for QTreeView:QString IPaddress and QString Name. (I want to show either of them on the QtreeView)

What is the best/proper way to do it?

class Object : public QObject
{
    Q_OBJECT
public:
//.... some properties, get and set functions, etc.
    QStandardItem *NodeItemIP;
    QStandardItem *NodeItemName;
private:
   QString Name;
   QString IPaddr;
///....
}

I store objects in a QVector: QVector<Object*> mObject

What I did to use QMap for each group to keep track

QMap<QString, QString> group1MapList;
QMap<QString, QString> group2MapList;
QMap<QString, QString> group3MapList;

and insert them to Qmap when they are appended to the QStandardItem

group1MapList.insert(mObject[1]->getName(), mObject[1]->getIPaddr());
Group1Item.appendRow(mObject[1]->NodeItemIP);

or

int index = 0;
QMap<QString, QString>::Iterator it;
for (it=group1MapList.begin(); it != group1MapList.end(); it++){
      if(it.value() == IPAddrToRemove){
      group1MapList.remove(IPAddrToRemove);
      Group1Item->removeRow(index);
      break;
   }
  index++;
}

I noticed that QMap (and QHash as well) does not store the entities in the order that they are added.

Is there any special class to keep track QStandardItems as I need or should I use QVector or anything else?

as I have two properties: IPaddr and Name, do I need to have two QVectors to track them or something can handle both of them?

Note: if there is no copy+paste/edit error, then above code snippets' syntax should be fine.


Solution

  • If you are working with QTreeView, maybe you must to create custom data structure to model the data tree. Something like this:

    struct ModelItem
    {
      QString groupName;
      QString name;
      QString IPaddr;
      ModelItem* parent;
      std::vector< ModelItem* > childs;
    
      ModelItem( const QString& a_name )
        : name( a_name ),
          parent( nullptr )
      { }
    
      ~ModelItem( )
      {
        for ( auto it = childs.begin( ); it != childs.end( ); ++it )
          delete *it;
      }
    
      void AddChild( ModelItem* children )
      {
        childs.push_back( children );
        children->parent = this;
      }
    };
    

    Of course, you need to subclass QAbstractItemModel:

    class CustomModel : public QAbstractItemModel
    {
        Q_OBJECT
    
      public:
    
        CustomModel( QObject* parent = nullptr );
    
        ~CustomModel( );
    
        int columnCount( const QModelIndex& parent ) const override;
    
        int rowCount( const QModelIndex& parent ) const override;
    
        QVariant data( const QModelIndex& index,
                       int role = Qt::DisplayRole ) const override;
    
        QModelIndex index ( int row,
                            int column,
                            const QModelIndex& parent ) const override;
    
        QModelIndex parent( const QModelIndex & index ) const override;
    
        void SetGroup( const QString& groupName,
                       const std::vector< std::pair< QString, QString > >& items );
    
        void ResetModel( );
    
      private:
    
        ModelItem rootNode;
    
    };
    

    columnCount and rowCount methods shall return the number of columns / rows of the model:

    int CustomModel::columnCount( const QModelIndex& /* parent */ ) const
    {
      return 1;
    }
    
    int CustomModel::rowCount( const QModelIndex& parent ) const
    {
    
      int to_return;
    
      if ( parent.isValid( ) )
      {
        ModelItem* node = static_cast< ModelItem* >( parent.internalPointer( ) );
        to_return = node->childs.size( );
      }
      else
        to_return = rootNode.childs.size( );
    
      return to_return;
    }
    

    data method shall return the content of the model:

    QVariant CustomModel::data( const QModelIndex& index,
                                int role ) const
    {
      QVariant to_return;
    
      if ( index.isValid( ) ) // if not valid, current index is root node
      {
        switch ( role )
        {
          case Qt::DisplayRole: // you can manage other roles to enrich the view
          {
            ModelItem* node = static_cast< ModelItem* >( index.internalPointer( ) );
            to_return = node->name;
            break;
          }
        }
      }
    
      return to_return;
    }
    

    index will create appropiate QModelIndex of given node:

    QModelIndex CustomModel::index ( int row,
                                     int column,
                                     const QModelIndex& parent ) const
    {
      QModelIndex to_return;
    
      if ( ( row >= 0 && row < rowCount( parent ) )
        && ( column >= 0 && column <= columnCount( parent ) ) )
      {
        if ( parent.isValid( ) )
        {
          ModelItem* item = static_cast< ModelItem* >( parent.internalPointer( ) );
          to_return = createIndex( row, column, item->childs.at( row ) );
        }
        else
        {
          to_return = createIndex( row, column, rootNode.childs.at( row ) );
        }
      }
    
      return to_return;
    }
    

    parent method shall return de index of the parent of given node

    QModelIndex CustomModel::parent( const QModelIndex & index ) const
    {
      QModelIndex to_return;
    
      if ( index.isValid( ) )
      {
        ModelItem* node = static_cast< ModelItem* >( index.internalPointer( ) );
        ModelItem* parent = node->parent;
        ModelItem* parent2 = parent->parent;
    
        if ( parent2 ) // node->parent can be root node
        {
          auto it = std::find_if( parent2->childs.begin( ), parent2->childs.end( ),
                                  [&]( ModelItem* child ){ return child == parent; } );
    
          if ( it != parent2->childs.end( ) )
          {
            int row = std::distance( parent2->childs.begin( ), it );
            to_return = createIndex( row, 0, parent );
          }
        }
      }
    
      return to_return;
    }
    

    Next method: SetGroup. With this method we can add data to the model:

    void CustomModel::SetGroup( const QString& groupName,
                                const std::vector< std::pair< QString, QString > >& items )
    {
      // Notify to view that we will insert a new group
      beginInsertRows( QModelIndex( ), rootNode.childs.size( ), rootNode.childs.size( ) );
    
      ModelItem* groupNode = new ModelItem( groupName );
      rootNode.AddChild( groupNode );
    
      for ( auto it = items.begin( ); it != items.end( ); ++it )
      {
        ModelItem* node = new ModelItem( it->first );
        node->name = it->first;
        node->IPaddr = it->second;
        groupNode->AddChild( node );
      }
    
      endInsertRows( );
    }
    

    ResetModel method simply clean the view:

    void CustomModel::ResetModel( )
    {
      beginResetModel( );
      rootNode= ModelItem( "root" );
      endResetModel( );
    }
    

    With model implementation completed, we only need to send data to model and link model and view:

    QTreeView* treeView_4 = new QTreeView( tab_10 );
    CustomModel* model = new CustomModel( this );
    
    std::vector< std::pair< QString, QString > > data;
    data.push_back( std::make_pair( "node1", "" ) );
    data.push_back( std::make_pair( "node2", "" ) );
    
    model->SetGroup( "Group 1", data );
    
    data.push_back( std::make_pair( "node3", "" ) );
    model->SetGroup( "Group 2", data );
    
    treeView4->setModel( model );