Bonjour à tous,

J'ai commencé à étudier PyQt depuis peu et je suis impressioné par les possibilités annoncées. J'ai trouvé un code intéressant ici http://www.shadoware.org/post/2009/0...C3%A9rarchique ([Qt] Transformation d'une vue tableau en une vue hiérarchique) car il correspond exactement au problème que je cherche à résoudre. Je l'ai traduit pour PyQt et j'ai ajouté un cadre général avec une vue table sur le modèle standard QSqlTableModel.

Pour espérer une synchronisation de la deuxième vue avec la vue table, il faut calculer les index de celle-ci en utilisant des requêtes QSqlQuery. L'écriture de la classe CategoryItemModel(QAbstractProxyModel) m'a montré que ce design est mauvais, car pour convertir un QModelIndex de l'arbre en QModelIndex de la table, il faut retrouver le numéro de ligne dans la table, ce qui est difficile en utilisant QSQLITE. Mais cela n'empêche pas de continuer puisque c'est du code expérimental.

Questions:

1) Y a-t-il une erreur (p.ex. choix des méthodes implémantées) dans le code ci-après qui empêche une synchronisation des deux vues ?

2) En activant les deux lignes après "test to connect selectionModel", j'obtiens le message suivant: QAbstractItemView::setSelectionModel() failed: Trying to set a selection model, which works on a different model than the view.

- Pourquoi Qt n'utilise-t-il pas les méthodes mapFromSource(), mapToSource() pour synchroniser les deux vues (en cliquant sur la dernière entrée de l'arbre je pensais que la dernière ligne de la table s'afficherait)

3) Peut-on conclure que l'emploi de QAbstractProxyModel n'apporte aucun avantage ? J'envisage une structure Python pour stocker les données sous leurs deux aspects et gérer les accès SQL, puis deux modèles distincts (un par vue). Qu'en pensez-vous ?

Merci d'avance pour vos avis.

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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
 
# -*- coding: latin1 -*-
#
#  - contient un accès à un modèle base de donnée sous forme de QSqlTableModel, vu par QTableView
#      et un deuxième CategoryItemModel(QAbstractProxyModel) vu par QTreeView
#      utilise directement SQL (via un groupe de QSqlQuery)
#
#  - WARN : ne tourne que sous Python 2.7.1 et PyQt v4.8.3
# 
 
import sys
 
from PyQt4.QtCore import *
from PyQt4.QtGui  import *
from PyQt4.QtSql  import *
 
ID = 0
ID_PARENT = 1
NAME = 2
 
import logging
logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s [%(levelname)s]: %(message)s",
                    datefmt="%Y.%m.%d/%H:%M:%S",
                    filename='zz-sql2-test.log',
                    filemode='a')
console = logging.StreamHandler()
# console.setLevel(logging.DEBUG)
console.setLevel(logging.WARN)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
 
 
#  --	--	--	--	--	--	--	--	--
#  --	A central object to locate a node within the tree  --	--
#  --	--	--	--	--	--	--	--	--
 
class Mapping(QObject):
    def __init__(self, owner, id, childPos, parentId, name, inTable=False):
        """
An object to store information about a node:
id = it's logical id
parentId = id-logique du noeud parent de la ligne key
name = the name value (only for debug)
inTable = say if childPos concern the TableView (or the Tree !)
        """
	super(Mapping, self).__init__(owner)
	self.owner = owner        # -- never used ?  But necessary for PyQt QObject ! --
        self.id = id
	self.childPos = childPos  # -- the position of id in its parent --
        self.parentId = parentId  # -- the parentId of this id
        self.name = name          # -- the name of this id
	self.inTable = inTable    # -- a flag to say if childPos is relative to the Table 
 
    def __repr__(self):
        return "Mapping(%d,%d,%d,%s,%s)" % (self.id, self.childPos, self.parentId, self.name, self.inTable)
 
    def isValid(self):
        # -- for strange situation -- A shadow object may exists, without attributes ~ --
        return hasattr(self, 'id')
 
 
#  --	--	--	--	--	--	--	--	--
 
class CategoryItemModel(QAbstractProxyModel):
    def __init__(self, db, parent):
        super(CategoryItemModel, self).__init__(parent)
	self.m_db = db
	self.parent = parent
 
    def select(self):
	# -- Prepare some queries: --
	self.query_children_count = QSqlQuery( self.m_db )
	self.query_children_count.prepare( "SELECT count(*) FROM subjects WHERE parent_id = :pid")
	self.query_children_id = QSqlQuery( self.m_db )
	self.query_children_id.prepare( "SELECT id, parent_id, name FROM subjects "
	                                "WHERE parent_id = :pid ORDER BY id")
	self.query_parent_id = QSqlQuery( self.m_db )
	self.query_parent_id.prepare( "SELECT parent_id, name FROM subjects WHERE id = :chid" )
	# -- @UPD@ this is only for the DEMONSTRATION ; very BAD design ! --
	self.query_element_ix = QSqlQuery( self.m_db )
	self.query_element_ix.prepare( "SELECT id, parent_id, name FROM subjects ORDER BY id")
 
	# -- Prepare a root element, to use model.createIndex(row, col, XXX) to access source info --
	model = self.sourceModel()
	self.rootIx = model.createIndex(-1,-1,None)  # -- always used to access data in rootModel --
	# -- Reset the layout
	self.reset()
	logging.info('%s.select(): end of reset()' % (self.__class__.__name__))
 
 
    def _get_children_count_(self, pid):
        # -- query about number of children for a parentid ; used with row_count() --
	self.query_children_count.bindValue(":pid", pid)
	self.query_children_count.exec_()
        self.query_children_count.next()
	if self.query_children_count.isValid():
	    children_count, fg_OK = self.query_children_count.value(0).toInt() 
	else:
	    children_count = 0
	logging.debug("_get_children_count_(%d) -> %d", pid, children_count)
	return children_count
 
 
    def _get_child_data_(self, chpos, pid):
	# -- use SQL to found the child data from its parentId and its relative row --
	# -- very BAD DESIGN, but allow test of it ! --
	self.query_children_id.bindValue(":pid", pid)
	self.query_children_id.exec_()
	xch = 0
	qname = None
        while self.query_children_id.next():
	    if xch == chpos:
	        qid, fg_OK = self.query_children_id.value(0).toInt()
		# -- qpid, fg_OK = self.query_children_id.value(1).toInt()
	        qname = self.query_children_id.value(2).toString()
	        break
	    xch += 1
	if qname is None:
	    qid = -1
	    xch = -1
	    qname = "[???]"
	rval = Mapping(self, qid, xch, pid, qname, False)
	logging.debug("_get_child_data_(%d, %d) -> %s", chpos, pid, repr(rval))
	return rval
 
 
    def _get_child_row_(self, id):
	# -- use SQL to found the parent and its relative row --
        parentId = self._get_parent_row_(id)
	if parentId < 0:
	   logging.debug("_get_child_row_(%d) -> None (because pid=%d)", id, parentId)
	   return None
 
	self.query_children_id.bindValue(":pid", parentId)
	self.query_children_id.exec_()
	xelm = 0
	qname = None
        while self.query_children_id.next():
	    qid, fg_OK = self.query_children_id.value(0).toInt()
	    # qname = self.query_children_id.value(2).toString()
	    # ldebug.append((qid, qname))
	    if qid == id:
	        qname = self.query_children_id.value(2).toString()
	        break
	    xelm += 1
	if qname is None:
	    qid = -1
	    qname = "[???]"
	rval = Mapping(self, qid, xelm, parentId, qname, False)
	logging.debug("_get_child_row_(%d) -> %s", id, repr(rval))
	return rval
 
 
    def _get_parent_row_(self, id):
	# -- use SQL to found the parent of child-id == id --
	self.query_parent_id.bindValue(":chid", id)
	self.query_parent_id.exec_()
        if self.query_parent_id.lastError().isValid():
     	    logging.warn("_get_parent_row_ has last error: %s" % (self.query_parent_id.lastError()))
	if self.query_parent_id.next():
            parentId, fg_OK = self.query_parent_id.value(0).toInt()
            parentName = self.query_parent_id.value(1).toString()
	else:
	   parentId = -2
	return parentId
 
 
    def _get_table_row_(self, id):
	# -- use SQL to found the relative row to the full table --
	# -- WARN : unefficient way !! --
	self.query_element_ix.exec_()
        if self.query_element_ix.lastError().isValid():
     	    print "DUMP: query_element_ix has last error: %s" % (self.query_element_ix.lastError())
 
	xelm = 0
	qname = None
        while self.query_element_ix.next():
	    qid, fg_OK = self.query_element_ix.value(0).toInt()
	    qname = self.query_element_ix.value(2).toString()
	    if qid == id:
                qparentId, fg_OK = self.query_element_ix.value(1).toInt()
	        break
	    xelm += 1
	    qname = None
	if qname is None:
	    qid = -1
	    qname = "[???]"
	rval = Mapping(self, qid, xelm, qparentId, qname, True)
	logging.debug("_get_table_row_(%d) -> %s", id, repr(rval))
	return rval
 
 
    def flags(self, index):
        defaultFlags = QAbstractItemModel.flags(self, index)
        if index.isValid():
            return Qt.ItemIsEditable | defaultFlags
        else:
            return defaultFlags
 
 
    def proxyColumnToSource(self, proxyColumn):
	if  proxyColumn == 0:
	    return NAME
	return -1
 
 
    def sourceColumnToProxy(self, sourceColumn):
	if  sourceColumn == NAME:
	    return 0
	return -1
 
 
    # -- For the given source index, this method return the corresponding index in the proxy
    def mapFromSource(self, sourceIndex):
        """from a sourceIndex, search the correspondant proxyIndex ; Only map the column NAME"""
	if not sourceIndex.isValid():
	    return QModelIndex()
 
	proxyColumn = self.sourceColumnToProxy( sourceIndex.column() )
	if proxyColumn == -1:
	    return QModelIndex()
 
	model = self.sourceModel()
	sixRow = sourceIndex.row()
	# -- create another SourceIndex to found the relevant rec.id --
	sixId = sourceIndex.sibling(sixRow, 0) 
	id, fg = sixId.data().toInt()
	logging.info("mapFromSource(%d,%d,...) id=%d", sourceIndex.row(), sourceIndex.column(), id)
 
	# -- to calculate the row, use SQL ? --
	map = self._get_child_row_(id)
	if map is None:
            logging.info("mapFromSource(%d,%d,...) deduce None (id=%d)", sourceIndex.row(), sourceIndex.column(), id)
            return QModelIndex()
	else:
            logging.info("mapFromSource(%d,%d,...) deduce (from id=%d) %s", sourceIndex.row(), sourceIndex.column(), repr(map), id)
            return self.createIndex(map.childPos, 0, map)
 
 
    def mapToSource(self, proxyIndex):
	if not proxyIndex.isValid():
	    return QModelIndex()
 
	sourceColumn = self.proxyColumnToSource( proxyIndex.column() )
	if sourceColumn == -1:
	    return QModelIndex()
 
	model = self.sourceModel()
	pmap = proxyIndex.internalPointer()
 
	if not pmap.isValid() or pmap.id < 0:
            # -- return model.createIndex(-1, -1, None)
	    logging.info("mapToSource(%s) -> source - index %d, %d", self._repr_index_(proxyIndex), tmap.childPos, sourceColumn)
	    return QModelIndex()
	else:
            tmap = self._get_table_row_(pmap.id)
	    logging.info("mapToSource(%s) -> source - index %d, %d", self._repr_index_(proxyIndex), tmap.childPos, sourceColumn)
            return model.createIndex(tmap.childPos, sourceColumn, None)
 
 
    def index(self, row, column, parent):
	if row < 0 or column < 0:
	    logging.info("index(%d, %d, ...) -> empty index", row, columns)
	    return QModelIndex()
 
        parentMap = parent.internalPointer()
	if parentMap is None:
	    parentId = 0
	else:
            parentId = parentMap.id
        proxy_map = self._get_child_data_(row, parentId)
	logging.info("index(%d, %d, %s) deduce %s", row, column, self._repr_index_(parent), repr(proxy_map))
        return self.createIndex(row, column, proxy_map)
 
 
    def parent(self, index):
	if not index.isValid():
	    return QModelIndex()
 
	currentMap = index.internalPointer()
	pid = currentMap.parentId 
	if pid < 0:
	    logging.info("parent(%s) -> invalid QModelIndex (because %s)", self._repr_index_(parent), repr(currentMap))
	    return QModelIndex()
 
	map = self._get_child_row_(pid)
	if map is None:
            logging.info("parent(%s) deduce empty index", self._repr_index_(index))
            return QModelIndex()
	else:
            logging.info("parent(%s) deduce %s", self._repr_index_(index), repr(map))
            return self.createIndex(map.childPos, 0, map)
 
 
    def hasChildren(self, index):
	if not index.isValid():
	    parentId = 0 
	else:
	    parentMap = index.internalPointer()
	    parentId = parentMap.id
 
        rowCount = self._get_children_count_(parentId)
	logging.info("hasChildren(%s) count %s rows", self._repr_index_(index), rowCount)
        return rowCount > 0
 
 
    def rowCount(self, index):
	if not index.isValid():
	    parentId = 0 
	else:
	    parentMap = index.internalPointer()
	    parentId = parentMap.id
 
        rowCount = self._get_children_count_(parentId)
	logging.info("rowCount(%s) -> %s", self._repr_index_(index), rowCount)
        return rowCount
 
 
    def columnCount(self, index):
	return 1
 
 
    def data(self, index, role=Qt.EditRole):
	if not index.isValid():
	    return QVariant()
 
        if role == Qt.DecorationRole:
            return QVariant()
        if role == Qt.TextAlignmentRole:
            return QVariant(int(Qt.AlignTop | Qt.AlignLeft))
        if role != Qt.DisplayRole and role != Qt.EditRole:
            return QVariant()
 
	if index.column() != 0:  # -- only column 0 is valid ! --
            return QVariant()
 
	# map = index.internalPointer()
	# logging.info("data(%s) -> %r" % (self._repr_index_(index), map.name))
	# return QVariant(QString(map.name))
	# -- Problem: if table updated, map isn't !
	# -- Then use the underlying model: --		
	model = self.sourceModel()
        sourceIndex = self.mapToSource( index )
        return model.data(sourceIndex)
 
    def _repr_index_(self, index):
        m = index.internalPointer()
        return "index(%d, %d, %s)" % (index.row(), index.column(), repr(m))
 
# -- ---------------------------------- --
# -- création de la vue et du conteneur --
# -- ---------------------------------- --
class MyWindow(QWidget):
    def __init__(self, *args):
        super(MyWindow, self).__init__(*args)
        self.setup_model()
	self.setup_proxy()
	# -- setup layout --
        layout = QVBoxLayout(self)
        layout.addWidget(self.tableView)
	layout.addWidget(self.proxyView)
        self.setLayout(layout)
 
 
    def setup_model(self):
        # -- setup the main Table model and View --
        # -- def a Sql model: 
        self.model = QSqlTableModel(self)
        self.model.setTable("subjects")
	self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        # -- 
        self.model.setHeaderData(ID, Qt.Horizontal, "Id")
        self.model.setHeaderData(ID_PARENT, Qt.Horizontal, "Id Parent")
        self.model.setHeaderData(NAME, Qt.Horizontal, "Name")
	# -- 
	self.model.setSort(ID, Qt.AscendingOrder) # -- to keep coherence with proxy --
        self.model.select()
	# -- 
        self.tableView = QTableView(self)
        self.tableView.setModel(self.model)
 
 
    def setup_proxy(self):
        # -- def a proxy model: -- 
	m_db = self.model.database()
        self.modelTree = CategoryItemModel(m_db, self)
	self.modelTree.setSourceModel( self.model )
	self.modelTree.select()
	# -- 
	self.test_proxy_model()
	# -- 
        self.proxyView = QTreeView(self)
	self.proxyView.setObjectName("treeView")
        # self.proxyView.setRootIsDecorated(False)
        self.proxyView.setAlternatingRowColors(True)
        self.proxyView.setModel(self.modelTree)
        self.proxyView.setSelectionMode(QAbstractItemView.SingleSelection)
 
	# -- test to connect selectionModel: --
	# self.selectionModel = self.tableView.selectionModel()
        # self.proxyView.setSelectionModel(self.selectionModel)
 
 
    def test_proxy_model(self):
        # -- test mecanism of index / rowCount --
	def show_children(index, depth=0):
	    data = model.data(index)
	    print "%s %s" % (' '*(2*depth), unicode(data.toString()))
	    crow = model.rowCount(index)
	    for xrow in range(crow):
	        chix = model.index(xrow, 0, index)
		show_children(chix, depth+1)
	# -- 
        print "Start of test_proxy_model()"
	model = self.modelTree
	rootix = model.createIndex(-1,-1,None)
	show_children(rootix)
        print "End of test_proxy_model()"
 
 
def createConnection():
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName('base.sqlite')
    if not db.open():
        QtGui.QMessageBox.critical(None, QtGui.qApp.tr("Cannot open database"),
                QtGui.qApp.tr("Unable to establish a database connection to SQLite.\n"
                              "Click Cancel to exit."),
                QtGui.QMessageBox.Cancel)
        return False
    query = QSqlQuery()
    fg_tab_ok = True
    fg_complete = False
    fg_complete_v2 = False
    fg_remove = False
    try:
        vv = query.exec_("select count(*) from subjects")
	if vv:
	    query.next()
            if query.isValid():
                val, fg_OK = query.value(0).toInt() # -- QVariant --
            else:
                logging.error("Invalid query or result! ")
		val = 0
        else:
	    fg_tab_ok = False
	    val = 0
	if val == 0:
	  fg_complete = True
	if val == 9:
	  fg_complete_v2 = True
	if val == 999:
	  fg_remove = True
    except Exception, iExc:
        fg_tab_ok = False
        print "raise exception %s: %s" % (iExc.__class__.__name__, str(iExc))
    if not fg_tab_ok:
	print "Create the table:"	
        query.exec_("create table subjects(id int primary key, "
                "parent_id int, name varchar(40))")
	fg_complete = True
    if fg_complete:
        query.exec_("insert into subjects values(1, 0, 'Categories')")
        query.exec_("insert into subjects values(3, 1, 'Webservices')")
        query.exec_("insert into subjects values(4, 1, 'Stylesheet')")
        query.exec_("insert into subjects values(7, 1, 'Buttons Widgets')")
        query.exec_("insert into subjects values(10, 7, 'Test2')")
        query.exec_("insert into subjects values(11, 7, 'Test3')")
        query.exec_("insert into subjects values(21, 0, 'Variants')")
        query.exec_("insert into subjects values(31, 21, 'Layout')")
        query.exec_("insert into subjects values(32, 21, 'Shortcut')")
        query.exec_("insert into subjects values(33, 31, 'H-Split')")
        query.exec_("insert into subjects values(36, 32, 'Copy')")
        query.exec_("insert into subjects values(37, 32, 'Paste')")
        query.exec_("commit")
    if fg_complete_v2:
	print "Complete (bis) the table with a root:"	
        query.exec_("insert into subjects values(34, 31, 'V-Split')")
        query.exec_("commit")
    if fg_remove:
	print "Remove invalid row from table:"	
        query.exec_("delete from subjects where id = 0")
	query.exec_("commit")
    return True
 
#===============================================================================
if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    if not createConnection():
        sys.exit(1)
 
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())