IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Qt Discussion :

QAbstractItemModel et QTreeView : recréer une arborescence à partir des données d'une table


Sujet :

Qt

  1. #1
    Membre régulier
    Profil pro
    Inscrit en
    Septembre 2003
    Messages
    98
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2003
    Messages : 98
    Points : 75
    Points
    75
    Par défaut QAbstractItemModel et QTreeView : recréer une arborescence à partir des données d'une table
    Bonjour

    J'essaye de faire un truc qui me semble pas extraordinaire mais je ne vois pas trop la meilleure facon de m'y prendre.

    Dans un QTreeView, je veux affichier les données d'un modèle dérivant de QAbstractItemModel.

    Les données sont elles mêmes stockées dans un vecteur de IRTFunctionDef.
    En gros ces objets stockent un nom de fonction et une "classification" qui correspond au noeud de l'arborescence que je voudrais afficher dans mon treeView;

    Voici la classe en question

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    class IRTFunctionDef
    	{
    	public:
    		IRTFunctionDef(string aFuncionName,  string aClassif)
    		{
    			m_functionName = aFuncionName;
                            m_classification = aClassif;
    		}
    		~IRTFunctionDef(){}
     
    		//Getters and setters
    		string getFunctionName() { return m_functionName; }
    		string getClassification() { return m_classification; }
    		string setFunctionName(string aVAl) { m_functionName = aVAl; }
    		string setClassification(string aVAl) { m_classification = aVAl; }
     
    	private:
    		string m_functionName;
    		string m_classification;
    	};
    l'attribut membre m_classification sera formaté ainsi : un/endroit/dans/mon/arbo

    Je souhaiterait donc que pour chacun des endroits de cet arbo désignés par les éléments de mon vector<IRTFunctionDef> un nouveau noeud soit créé dans mon treeView et que ce noeud contienne toutes les noms de fonctions qui ont cet emplacement en commun.

    Je ne vois pas trop comment implémenter les fonctions index(..) et parent(..) pour faire cela.
    Je ne vois pas trop également si je dois stocker cette pseudo arobrescence dans mon model ou si je peux m'en sortir avec les informations contenues dans mon vecteur<IRTFonctionDef>

    J'espère que j'ai été assez clair,
    Merci d'avance pour votre aide.


    Traiangueul

  2. #2
    Membre régulier
    Profil pro
    Inscrit en
    Septembre 2003
    Messages
    98
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2003
    Messages : 98
    Points : 75
    Points
    75
    Par défaut
    Bon,
    je crois que je m'en suis sorti.

    Ma solution (brute de fonderie) pour la postérité et pour les éventuelles améliorations que vous pourriez suggérer :

    Je me suis très largement inspiré de ce tuto http://http://doc.qt.io/qt-5/qtwidge...l-example.html

    header:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    #ifndef FUNCTIONTABLEMODEL_H
    #define FUNCTIONTABLEMODEL_H
     
    //IRT
    #include "xmlrpctypes.h"
     
    // QT
    #include <qabstractitemmodel.h>
    #include <qstring.h>
    #include <qmap.h>
     
    using namespace xmlRpcClient;
     
    //anticipated declarations
    class TreeItem;
     
    class FunctionTableModel : public QAbstractItemModel
    {
    public:
    	FunctionTableModel(QObject * parent = 0);
    	~FunctionTableModel();
     
    	//subclassing QAbstarcItemModel
     
     
    	virtual QModelIndex	index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
    	virtual QModelIndex	parent(const QModelIndex & index) const;
    	virtual int	rowCount(const QModelIndex & parent = QModelIndex()) const;
    	virtual int columnCount(const QModelIndex & parent = QModelIndex()) const;
    	virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
    	virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
     
    	//setHeaderData()
     
    	//maybe
    	//hasChildren()
     
    	// headerDataChanged() ??????
    	//To create models that populate incrementally, you can reimplement fetchMore() and canFetchMore().If the reimplementation of fetchMore() adds rows to the model, beginInsertRows() and endInsertRows() must be called.
     
    	static FunctionTableModel* getInstance();
     
    	void setupModelData();
     
    private:
    	Statused<Countable<IRTFunctionDef> >* m_data;
     
    	//map holding classification with corresponding TreeItem 
    	QMap<QString, TreeItem*> m_classificationToTreeItemMap;
    	TreeItem* m_rootItem;
     
    	static FunctionTableModel* m_instance;
     
    };
     
     
    class TreeItem
    {
    public:
    	explicit TreeItem(const IRTFunctionDef &data, TreeItem *parentItem = 0);
    	~TreeItem();
     
    	void appendChild(TreeItem *child);
     
    	TreeItem *child(int row);
    	int childCount() const;
    	int columnCount() const;
    	QVariant data(int column, bool bIsLeaf) const;
    	int row() const;
    	TreeItem *parentItem();
     
    private:
    	QList<TreeItem*> m_childItems;
    	IRTFunctionDef m_itemData;
    	TreeItem *m_parentItem;
    };
     
    #endif //FUNCTIONTABLEMODEL_H
    source:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    //IRT 
    #include "functiontablemodel.h"
    #include "singletonmanager.h"
     
    //QT
    #include <qmap.h>
    #include <QtGlobal>
    #include <qdebug.h>
     
    //STD
    #include "assert.h"
     
    FunctionTableModel* FunctionTableModel::m_instance = NULL;
     
    string m_headers[] = { string("Classification/Name"), string("date"), string("standard"), string("id"), string("author"), string("message") };
     
    FunctionTableModel* FunctionTableModel::getInstance()
    {
    	if (m_instance == NULL)
    	{
    		m_instance = new FunctionTableModel();
    	}
    	return m_instance;
    }
     
     
    FunctionTableModel::FunctionTableModel(QObject * parent) : QAbstractItemModel(parent)
    {
    	//m_classificationToTreeItemMap = QMap<QString, TreeItem*>();
    	m_data = NULL;
    	//m_classificationToTreeItemMap.clear();
    	m_rootItem = new TreeItem(IRTFunctionDef());
     
    }
     
    QVariant FunctionTableModel::headerData(int section, Qt::Orientation orientation, int role) const
    {
    	if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
    	{	
    		return QVariant(m_headers[section].c_str());
    	}
    	else
    		return QVariant::Invalid;
    }
     
    FunctionTableModel::~FunctionTableModel()
    {
    }
     
     
     
     
    QModelIndex	FunctionTableModel::index(int row, int column, const QModelIndex & parent ) const
    {
     
    	if (!hasIndex(row, column, parent))
    		return QModelIndex();
     
    	TreeItem *parentItem;
     
    	if (!parent.isValid())
    		parentItem = m_rootItem;
    	else
    		parentItem = static_cast<TreeItem*>(parent.internalPointer());
     
    	TreeItem *childItem = parentItem->child(row);
    	if (childItem)
    		return createIndex(row, column, childItem);
    	else
    		return QModelIndex();
     
    }
     
    QModelIndex	FunctionTableModel::parent(const QModelIndex & index) const
    {
    	if (!index.isValid())
    		return QModelIndex();
     
    	TreeItem *childItem = static_cast<TreeItem*>(index.internalPointer());
    	TreeItem *parentItem = childItem->parentItem();
     
    	if (parentItem == m_rootItem)
    		return QModelIndex();
     
    	return createIndex(parentItem->row(), 0, parentItem);
    }
     
    int	FunctionTableModel::rowCount(const QModelIndex & parent) const
    {
    	TreeItem *parentItem;
    	if (parent.column() > 0)
    		return 0;
     
    	if (!parent.isValid())
    		parentItem = m_rootItem;
    	else
    		parentItem = static_cast<TreeItem*>(parent.internalPointer());
     
    	return parentItem->childCount(); 
     
    }
     
    int FunctionTableModel::columnCount(const QModelIndex & parent ) const
    {
    	//columns are : S_AUTHOR_LABEL, S_CREATION_DATE_LABEL, S_MESSAGE_LABEL
    	//function type, S_CLASSIFICATION_LABEL/function name(in same column), function db ID
    	// maybe one more column with all parameters for the given filter ? //TODO TBC
     
    	return 6;
    }
     
    QVariant FunctionTableModel::data(const QModelIndex & index, int role) const
    {
    	if (!index.isValid())
    		return QVariant();
     
    	if (role != Qt::DisplayRole)
    		return QVariant();
     
    	TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
     
    	bool bIsLeaf = true;
    	bIsLeaf = (item->childCount() == 0);
    	return item->data(index.column(), bIsLeaf);
     
    }
     
     
    void FunctionTableModel::setupModelData()
    {
    	//clear current data:
    	emit(beginResetModel());
    	if (m_data != NULL){
    		delete m_data;
    		m_data = NULL;
    	}
    	//rebuild list of criteria
    	std::pair<string, string> tmp;
    	tmp.first = "name";
    	tmp.first = "toto";
     
    	vector < std::pair<string, string>> vect;
    	vect.push_back(tmp);
    	Statused<Countable<IRTFunctionDef> >* lData = SingletonManager::xmlRpcClient()->getIRTFunctionsMatching(0, vect);
     
    	for (int idxFunction = 0; idxFunction < lData->getObj()->getSize(); idxFunction++)
    	{
    		IRTFunctionDef lCurrentFunction = lData->getObj()->getObjectAt(idxFunction); 
     
    		QString lstrClassif = QString::fromStdString(lCurrentFunction.getClassification());
     
    		//remove initial and/or final '/' if any :
    		while (lstrClassif.endsWith('/')) lstrClassif.chop(1);
    		while (lstrClassif.startsWith('/')) lstrClassif.remove(0,1);
     
    		//add current function as a child of the classification node
    		if (m_classificationToTreeItemMap.find(lstrClassif) != m_classificationToTreeItemMap.end())
    		{
    			//we first are hoptimistic supposing treeItem is already there
     
    			//lets add function in tree node
    			TreeItem * lfoundParent = m_classificationToTreeItemMap.find(lstrClassif).value();
    			TreeItem * leafTreeNode = new TreeItem(lCurrentFunction,lfoundParent);
    			lfoundParent->appendChild(leafTreeNode);
    		}
    		else
    		{
    			//node is not already known
    			//lets create it as a child of its parent (yes!)
     
    			QStringList strClassifParts = lstrClassif.split(QString::fromStdString("/"), QString::SkipEmptyParts);
    			QString strReconstructedClassif = "";
    			TreeItem* lParent = m_rootItem;
    			TreeItem* lCurentNode = NULL;
    			bool bAtLesatSecodnPart = false;
    			while (!strClassifParts.isEmpty())
    			{
    				if (bAtLesatSecodnPart)
    				{
    					strReconstructedClassif += QString("/");
    				}
    				QString strCurrentPart = strClassifParts.takeFirst();
    				bAtLesatSecodnPart = true;
    				strReconstructedClassif += strCurrentPart;
     
    				if (m_classificationToTreeItemMap.find(strReconstructedClassif) == m_classificationToTreeItemMap.end())
    				{//then add it
    					//create new IRT function object
    					IRTFunctionDef function;
     
    					//set is classifiation and name with current part of path
    					function.setFunctionName(strCurrentPart.toStdString());
    					function.setClassification(strReconstructedClassif.toStdString());
     
    					//crete new treeITem
    					TreeItem* newNode = new TreeItem(function, lParent);
     
    					//add it as a child of its parent (eys, really)
    					lParent->appendChild(newNode);
     
    					//remember it in map so we don't recreate it later on
    					m_classificationToTreeItemMap[strReconstructedClassif] = newNode;
    				}
     
     
    				//prepare next iteration
    				assert(m_classificationToTreeItemMap.find(strReconstructedClassif) != m_classificationToTreeItemMap.end());
    				lParent = m_classificationToTreeItemMap.find(strReconstructedClassif).value();
    			}
     
    			//at this point all tree should be created to access lStrClassif
    			assert(m_classificationToTreeItemMap.find(lstrClassif) != m_classificationToTreeItemMap.end());
     
    			TreeItem * lfoundParent = m_classificationToTreeItemMap.find(lstrClassif).value();
    			TreeItem * leafTreeNode = new TreeItem(lCurrentFunction, lfoundParent);
    			lfoundParent->appendChild(leafTreeNode);
     
    		}// node not already there, we need to create it (and maybe parents)
     
     
    	}
     
    	emit(endResetModel());
     
    }
     
     
     
     
     
    TreeItem::TreeItem(const IRTFunctionDef &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::row() const
    {
    	if (m_parentItem)
    		return m_parentItem->m_childItems.indexOf(const_cast<TreeItem*>(this));
     
    	return 0;
    }
     
    int TreeItem::columnCount() const
    {
    	return 7;
    }
     
    QVariant TreeItem::data(int column, bool bIsLeaf) const
    {
    	m_itemData.getAuthor();
    	string lstrData = "";
    	switch (column)
    	{
    	case 0:
     
    		lstrData = m_itemData.getFunctionName();
    		break;
    	case 1:
    		lstrData = m_itemData.getCreationDate();
    		break;
    	case 2:
    		lstrData = m_itemData.getStandard();
    		break;
    	case 3:
    		lstrData = m_itemData.getDbId();
    		break;
    	case 4:
    		lstrData = m_itemData.getAuthor();
    		break;
    	case 5:
    		lstrData = m_itemData.getMessage();
    		break;
    	default:
    		lstrData = (string("col") + std::to_string(column));
    		break;
    	}
     
    	if (lstrData == s_UNDEF_STRING)
    	{
    		return QVariant();
    	}
    	return QVariant(QString::fromStdString(lstrData));
    }
     
    TreeItem *TreeItem::parentItem()
    {
    	return m_parentItem;
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 3
    Dernier message: 13/08/2014, 18h14
  2. Dessiner des graphiques à partir des données d'une BD MySQL
    Par condor_01 dans le forum Général Java
    Réponses: 6
    Dernier message: 24/04/2008, 09h35
  3. comment concevoir un etat à partir des données d'une base de données
    Par lylyagloire dans le forum Interfaces Graphiques en Java
    Réponses: 1
    Dernier message: 26/03/2007, 19h23
  4. Une infobulle à partir des coordonnées sur une image
    Par dark_vidor dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 28/01/2006, 21h20
  5. réafficher une image à partir des données recupérées
    Par vbcasimir dans le forum Langage
    Réponses: 3
    Dernier message: 04/10/2005, 10h50

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo