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
| #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PyQt5 import (QtWidgets, QtGui, QtCore)
#############################################################################
class TreeWidget(QtWidgets.QTreeWidget):
# =======================================================================
def __init__(self, parent=None):
super().__init__(parent)
self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)#self.ExtendedSelection)
self.setAcceptDrops(True)
self.setDragDropMode(self.InternalMove)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setDropIndicatorShown(True)
#############################################################################
class Fenetre(QtWidgets.QWidget):
# =======================================================================
def __init__(self, parent=None):
super().__init__(parent)
self.resize(800, 600)
self.setWindowTitle("Affiche arbre")
self.tw = TreeWidget(self)
self.tw.setColumnCount(3)
self.tw.setHeaderLabels(["Column 1", "Column 2", "Column 3"])
l1 = QtWidgets.QTreeWidgetItem(["String A", "String B", "String C"])
self.tw.addTopLevelItem(l1)
for i in range(0, 3):
l1_child = QtWidgets.QTreeWidgetItem(["Child 1A" + str(i), "Child 1B" + str(i), "Child 1C" + str(i)])
l1.addChild(l1_child)
for i in range(0, 3):
l1_child = QtWidgets.QTreeWidgetItem(["Child 2A" + str(i), "Child 2B" + str(i), "Child 2C" + str(i)])
l1.child(1).addChild(l1_child)
for i in range(0, 3):
l1_child = QtWidgets.QTreeWidgetItem(["Child 3A" + str(i), "Child 3B" + str(i), "Child 3C" + str(i)])
l1.child(1).child(0).addChild(l1_child)
layout = QtWidgets.QGridLayout()
layout.addWidget(self.tw, 0, 0)
self.setLayout(layout)
# développe l'arborescence
self.tw.expandAll()
#self.tw.expandToDepth(0) # développe seulement le niveau 0
#self.tw.expandToDepth(1) # développe les niveaux 0 et 1
# ajuste la largeur des colonnes à leur contenu
for col in range(0, self.tw.columnCount()):
self.tw.resizeColumnToContents(col)
# =======================================================================
def keyPressEvent(self, event):
"""raccourcis clavier
"""
if self.tw.hasFocus():
if event.key() == QtCore.Qt.Key_E and (event.modifiers() & QtCore.Qt.AltModifier):
self.tw.expandAll()
#self.tw.expandToDepth(0)
#self.tw.topLevelItem(0).child(0).setSelected(True)
# ajuste la largeur des colonnes à leur contenu
for col in range(0, self.tw.columnCount()):
self.tw.resizeColumnToContents(col)
event.accept()
else:
event.ignore()
super().keyPressEvent(event)
#############################################################################
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
fen = Fenetre()
fen.show()
sys.exit(app.exec_()) |
Partager