0
# Model-View Widgets
1
2
Data-driven widgets using the Model-View pattern including tables and trees with support for various data sources and custom models.
3
4
## Capabilities
5
6
### Abstract Base Classes
7
8
Base classes for implementing the Model-View architecture pattern.
9
10
```python { .api }
11
class TTkAbstractItemModel:
12
def __init__(self, parent=None):
13
"""Initialize abstract item model."""
14
15
def rowCount(self, parent=None):
16
"""Get number of rows in the model."""
17
18
def columnCount(self, parent=None):
19
"""Get number of columns in the model."""
20
21
def data(self, index, role=None):
22
"""Get data for the specified model index and role."""
23
24
def setData(self, index, value, role=None):
25
"""Set data for the specified model index and role."""
26
27
def headerData(self, section, orientation, role=None):
28
"""Get header data for the specified section."""
29
30
def flags(self, index):
31
"""Get item flags for the specified index."""
32
33
def index(self, row, column, parent=None):
34
"""Create a model index for the specified position."""
35
36
def parent(self, index):
37
"""Get the parent index for the specified index."""
38
39
def hasChildren(self, parent=None):
40
"""Check if the specified index has children."""
41
42
def insertRows(self, row, count, parent=None):
43
"""Insert rows into the model."""
44
45
def removeRows(self, row, count, parent=None):
46
"""Remove rows from the model."""
47
48
def insertColumns(self, column, count, parent=None):
49
"""Insert columns into the model."""
50
51
def removeColumns(self, column, count, parent=None):
52
"""Remove columns from the model."""
53
54
# Signals
55
dataChanged: pyTTkSignal # Emitted when data changes
56
rowsInserted: pyTTkSignal # Emitted when rows are inserted
57
rowsRemoved: pyTTkSignal # Emitted when rows are removed
58
columnsInserted: pyTTkSignal # Emitted when columns are inserted
59
columnsRemoved: pyTTkSignal # Emitted when columns are removed
60
modelReset: pyTTkSignal # Emitted when model is reset
61
62
class TTkAbstractTableModel(TTkAbstractItemModel):
63
def __init__(self, parent=None):
64
"""Initialize abstract table model."""
65
66
def rowCount(self, parent=None):
67
"""Get number of rows in the table."""
68
69
def columnCount(self, parent=None):
70
"""Get number of columns in the table."""
71
72
def data(self, index, role=None):
73
"""Get data for table cell."""
74
75
def setData(self, index, value, role=None):
76
"""Set data for table cell."""
77
78
def headerData(self, section, orientation, role=None):
79
"""Get header data for row or column."""
80
81
class TTkModelIndex:
82
def __init__(self, row=-1, column=-1, parent=None, model=None):
83
"""
84
Initialize a model index.
85
86
Parameters:
87
- row (int): Row number
88
- column (int): Column number
89
- parent: Parent index
90
- model: Associated model
91
"""
92
93
def row(self):
94
"""Get the row number."""
95
96
def column(self):
97
"""Get the column number."""
98
99
def parent(self):
100
"""Get the parent index."""
101
102
def model(self):
103
"""Get the associated model."""
104
105
def isValid(self):
106
"""Check if the index is valid."""
107
108
def data(self, role=None):
109
"""Get data from the model for this index."""
110
111
def sibling(self, row, column):
112
"""Get sibling index at specified row and column."""
113
```
114
115
### Table Widgets
116
117
Table widgets for displaying and editing tabular data.
118
119
```python { .api }
120
class TTkTable(TTkAbstractScrollArea):
121
def __init__(self, parent=None, **kwargs):
122
"""
123
Initialize a table widget.
124
125
Parameters:
126
- model: Data model for the table
127
"""
128
129
def setModel(self, model):
130
"""Set the data model for the table."""
131
132
def model(self):
133
"""Get the current data model."""
134
135
def setSelectionBehavior(self, behavior):
136
"""Set selection behavior (rows, columns, items)."""
137
138
def selectionBehavior(self):
139
"""Get current selection behavior."""
140
141
def setSelectionMode(self, mode):
142
"""Set selection mode (single, multi, extended)."""
143
144
def selectionMode(self):
145
"""Get current selection mode."""
146
147
def currentIndex(self):
148
"""Get current selected index."""
149
150
def setCurrentIndex(self, index):
151
"""Set current selected index."""
152
153
def selectedIndexes(self):
154
"""Get list of selected indexes."""
155
156
def selectRow(self, row):
157
"""Select entire row."""
158
159
def selectColumn(self, column):
160
"""Select entire column."""
161
162
def clearSelection(self):
163
"""Clear current selection."""
164
165
def setRowHeight(self, row, height):
166
"""Set height for specific row."""
167
168
def setColumnWidth(self, column, width):
169
"""Set width for specific column."""
170
171
def rowHeight(self, row):
172
"""Get height of specific row."""
173
174
def columnWidth(self, column):
175
"""Get width of specific column."""
176
177
def hideRow(self, row):
178
"""Hide specific row."""
179
180
def hideColumn(self, column):
181
"""Hide specific column."""
182
183
def showRow(self, row):
184
"""Show specific row."""
185
186
def showColumn(self, column):
187
"""Show specific column."""
188
189
def isRowHidden(self, row):
190
"""Check if row is hidden."""
191
192
def isColumnHidden(self, column):
193
"""Check if column is hidden."""
194
195
def resizeRowsToContents(self):
196
"""Resize all rows to fit content."""
197
198
def resizeColumnsToContents(self):
199
"""Resize all columns to fit content."""
200
201
# Signals
202
clicked: pyTTkSignal # Emitted when cell is clicked
203
doubleClicked: pyTTkSignal # Emitted when cell is double-clicked
204
entered: pyTTkSignal # Emitted when mouse enters cell
205
pressed: pyTTkSignal # Emitted when cell is pressed
206
207
class TTkTableWidget(TTkTable):
208
def __init__(self, parent=None, **kwargs):
209
"""
210
Initialize a table widget with built-in model.
211
212
Parameters:
213
- rows (int): Number of rows
214
- columns (int): Number of columns
215
"""
216
217
def setRowCount(self, rows):
218
"""Set number of rows."""
219
220
def setColumnCount(self, columns):
221
"""Set number of columns."""
222
223
def rowCount(self):
224
"""Get number of rows."""
225
226
def columnCount(self):
227
"""Get number of columns."""
228
229
def setItem(self, row, column, item):
230
"""Set item at specified position."""
231
232
def item(self, row, column):
233
"""Get item at specified position."""
234
235
def takeItem(self, row, column):
236
"""Remove and return item at position."""
237
238
def setHorizontalHeaderLabels(self, labels):
239
"""Set horizontal header labels."""
240
241
def setVerticalHeaderLabels(self, labels):
242
"""Set vertical header labels."""
243
244
def horizontalHeaderItem(self, column):
245
"""Get horizontal header item."""
246
247
def verticalHeaderItem(self, row):
248
"""Get vertical header item."""
249
250
def setHorizontalHeaderItem(self, column, item):
251
"""Set horizontal header item."""
252
253
def setVerticalHeaderItem(self, row, item):
254
"""Set vertical header item."""
255
256
def clear(self):
257
"""Clear all items."""
258
259
def clearContents(self):
260
"""Clear item contents but keep headers."""
261
262
class TTkHeaderView(TTkWidget):
263
def __init__(self, orientation, parent=None):
264
"""
265
Initialize a header view.
266
267
Parameters:
268
- orientation: Horizontal or vertical orientation
269
"""
270
271
def setModel(self, model):
272
"""Set the model for the header."""
273
274
def model(self):
275
"""Get the current model."""
276
277
def setOrientation(self, orientation):
278
"""Set header orientation."""
279
280
def orientation(self):
281
"""Get header orientation."""
282
283
def setSectionResizeMode(self, mode):
284
"""Set section resize mode."""
285
286
def sectionResizeMode(self):
287
"""Get section resize mode."""
288
289
def setStretchLastSection(self, stretch):
290
"""Set whether last section stretches."""
291
292
def stretchLastSection(self):
293
"""Check if last section stretches."""
294
295
def resizeSection(self, section, size):
296
"""Resize specific section."""
297
298
def sectionSize(self, section):
299
"""Get size of specific section."""
300
301
def hideSection(self, section):
302
"""Hide specific section."""
303
304
def showSection(self, section):
305
"""Show specific section."""
306
307
def isSectionHidden(self, section):
308
"""Check if section is hidden."""
309
```
310
311
### Tree Widgets
312
313
Tree widgets for displaying hierarchical data structures.
314
315
```python { .api }
316
class TTkTree(TTkAbstractScrollArea):
317
def __init__(self, parent=None, **kwargs):
318
"""Initialize a tree widget."""
319
320
def setModel(self, model):
321
"""Set the data model for the tree."""
322
323
def model(self):
324
"""Get the current data model."""
325
326
def setRootIndex(self, index):
327
"""Set the root index for the tree view."""
328
329
def rootIndex(self):
330
"""Get the root index."""
331
332
def currentIndex(self):
333
"""Get current selected index."""
334
335
def setCurrentIndex(self, index):
336
"""Set current selected index."""
337
338
def selectedIndexes(self):
339
"""Get list of selected indexes."""
340
341
def expand(self, index):
342
"""Expand item at index."""
343
344
def collapse(self, index):
345
"""Collapse item at index."""
346
347
def isExpanded(self, index):
348
"""Check if item is expanded."""
349
350
def expandAll(self):
351
"""Expand all items."""
352
353
def collapseAll(self):
354
"""Collapse all items."""
355
356
def setItemsExpandable(self, expandable):
357
"""Set whether items are expandable."""
358
359
def itemsExpandable(self):
360
"""Check if items are expandable."""
361
362
def setAutoExpandDelay(self, delay):
363
"""Set auto-expand delay in milliseconds."""
364
365
def autoExpandDelay(self):
366
"""Get auto-expand delay."""
367
368
def setIndentation(self, indentation):
369
"""Set indentation width."""
370
371
def indentation(self):
372
"""Get indentation width."""
373
374
def setUniformRowHeights(self, uniform):
375
"""Set whether all rows have uniform height."""
376
377
def uniformRowHeights(self):
378
"""Check if rows have uniform height."""
379
380
# Signals
381
clicked: pyTTkSignal # Emitted when item is clicked
382
doubleClicked: pyTTkSignal # Emitted when item is double-clicked
383
expanded: pyTTkSignal # Emitted when item is expanded
384
collapsed: pyTTkSignal # Emitted when item is collapsed
385
386
class TTkTreeWidget(TTkTree):
387
def __init__(self, parent=None, **kwargs):
388
"""Initialize a tree widget with built-in model."""
389
390
def setColumnCount(self, columns):
391
"""Set number of columns."""
392
393
def columnCount(self):
394
"""Get number of columns."""
395
396
def setHeaderLabels(self, labels):
397
"""Set header labels for columns."""
398
399
def headerItem(self):
400
"""Get header item."""
401
402
def setHeaderItem(self, item):
403
"""Set header item."""
404
405
def invisibleRootItem(self):
406
"""Get invisible root item."""
407
408
def addTopLevelItem(self, item):
409
"""Add top-level item."""
410
411
def insertTopLevelItem(self, index, item):
412
"""Insert top-level item at index."""
413
414
def takeTopLevelItem(self, index):
415
"""Remove and return top-level item."""
416
417
def topLevelItemCount(self):
418
"""Get number of top-level items."""
419
420
def topLevelItem(self, index):
421
"""Get top-level item at index."""
422
423
def currentItem(self):
424
"""Get current selected item."""
425
426
def setCurrentItem(self, item):
427
"""Set current selected item."""
428
429
def selectedItems(self):
430
"""Get list of selected items."""
431
432
def findItems(self, text, flags):
433
"""Find items by text and flags."""
434
435
def clear(self):
436
"""Clear all items."""
437
438
class TTkTreeWidgetItem:
439
def __init__(self, parent=None, strings=None):
440
"""
441
Initialize a tree widget item.
442
443
Parameters:
444
- parent: Parent item or tree widget
445
- strings: List of column texts
446
"""
447
448
def setText(self, column, text):
449
"""Set text for specific column."""
450
451
def text(self, column):
452
"""Get text for specific column."""
453
454
def setIcon(self, column, icon):
455
"""Set icon for specific column."""
456
457
def icon(self, column):
458
"""Get icon for specific column."""
459
460
def setData(self, column, role, value):
461
"""Set data for column and role."""
462
463
def data(self, column, role):
464
"""Get data for column and role."""
465
466
def setFlags(self, flags):
467
"""Set item flags."""
468
469
def flags(self):
470
"""Get item flags."""
471
472
def parent(self):
473
"""Get parent item."""
474
475
def child(self, index):
476
"""Get child item at index."""
477
478
def childCount(self):
479
"""Get number of child items."""
480
481
def addChild(self, child):
482
"""Add child item."""
483
484
def insertChild(self, index, child):
485
"""Insert child item at index."""
486
487
def takeChild(self, index):
488
"""Remove and return child item."""
489
490
def removeChild(self, child):
491
"""Remove child item."""
492
493
def indexOfChild(self, child):
494
"""Get index of child item."""
495
496
def setExpanded(self, expanded):
497
"""Set expanded state."""
498
499
def isExpanded(self):
500
"""Check if item is expanded."""
501
502
def setSelected(self, selected):
503
"""Set selected state."""
504
505
def isSelected(self):
506
"""Check if item is selected."""
507
508
def setHidden(self, hidden):
509
"""Set hidden state."""
510
511
def isHidden(self):
512
"""Check if item is hidden."""
513
514
def clone(self):
515
"""Create a copy of this item."""
516
```
517
518
### Table Data Models
519
520
Concrete implementations of table models for different data sources.
521
522
```python { .api }
523
class TTkTableModelList(TTkAbstractTableModel):
524
def __init__(self, data=None):
525
"""
526
Initialize table model with list data.
527
528
Parameters:
529
- data: List of lists representing table data
530
"""
531
532
def setData(self, data):
533
"""Set the table data."""
534
535
def data(self):
536
"""Get the table data."""
537
538
def addRow(self, row_data):
539
"""Add a row to the table."""
540
541
def insertRow(self, index, row_data):
542
"""Insert a row at specific index."""
543
544
def removeRow(self, index):
545
"""Remove row at index."""
546
547
def addColumn(self, column_data):
548
"""Add a column to the table."""
549
550
def insertColumn(self, index, column_data):
551
"""Insert a column at specific index."""
552
553
def removeColumn(self, index):
554
"""Remove column at index."""
555
556
def setHeaders(self, headers):
557
"""Set column headers."""
558
559
def headers(self):
560
"""Get column headers."""
561
562
class TTkTableModelCSV(TTkAbstractTableModel):
563
def __init__(self, filename=None):
564
"""
565
Initialize table model with CSV data.
566
567
Parameters:
568
- filename (str): Path to CSV file
569
"""
570
571
def loadFromFile(self, filename):
572
"""Load data from CSV file."""
573
574
def saveToFile(self, filename):
575
"""Save data to CSV file."""
576
577
def setDelimiter(self, delimiter):
578
"""Set CSV delimiter character."""
579
580
def delimiter(self):
581
"""Get CSV delimiter character."""
582
583
def setHasHeader(self, has_header):
584
"""Set whether CSV has header row."""
585
586
def hasHeader(self):
587
"""Check if CSV has header row."""
588
589
class TTkTableModelSQLite3(TTkAbstractTableModel):
590
def __init__(self, database=None):
591
"""
592
Initialize table model with SQLite database.
593
594
Parameters:
595
- database (str): Path to SQLite database file
596
"""
597
598
def setDatabase(self, database):
599
"""Set database connection."""
600
601
def database(self):
602
"""Get database connection."""
603
604
def setTable(self, table_name):
605
"""Set table name to query."""
606
607
def table(self):
608
"""Get current table name."""
609
610
def setQuery(self, query):
611
"""Set custom SQL query."""
612
613
def query(self):
614
"""Get current SQL query."""
615
616
def refresh(self):
617
"""Refresh data from database."""
618
619
def submitAll(self):
620
"""Submit all changes to database."""
621
622
def revertAll(self):
623
"""Revert all changes."""
624
```
625
626
### File Tree Widgets
627
628
Specialized tree widgets for displaying file system structures.
629
630
```python { .api }
631
class TTkFileTree(TTkTree):
632
def __init__(self, parent=None, **kwargs):
633
"""Initialize a file tree widget."""
634
635
def setRootPath(self, path):
636
"""Set root directory path."""
637
638
def rootPath(self):
639
"""Get root directory path."""
640
641
def setNameFilters(self, filters):
642
"""Set file name filters."""
643
644
def nameFilters(self):
645
"""Get file name filters."""
646
647
def setFilter(self, filter_flags):
648
"""Set file filter flags."""
649
650
def filter(self):
651
"""Get file filter flags."""
652
653
def refresh(self):
654
"""Refresh file tree."""
655
656
def mkdir(self, path):
657
"""Create directory."""
658
659
def remove(self, path):
660
"""Remove file or directory."""
661
662
def filePath(self, index):
663
"""Get file path for index."""
664
665
def fileName(self, index):
666
"""Get file name for index."""
667
668
def fileInfo(self, index):
669
"""Get file information for index."""
670
671
def isDir(self, index):
672
"""Check if index represents directory."""
673
674
class TTkFileTreeWidget(TTkFileTree):
675
def __init__(self, parent=None, **kwargs):
676
"""Initialize file tree widget with built-in model."""
677
678
def currentPath(self):
679
"""Get current selected path."""
680
681
def setCurrentPath(self, path):
682
"""Set current selected path."""
683
684
def selectedPaths(self):
685
"""Get list of selected paths."""
686
687
class TTkFileTreeWidgetItem(TTkTreeWidgetItem):
688
def __init__(self, parent=None, path=""):
689
"""
690
Initialize file tree item.
691
692
Parameters:
693
- parent: Parent item
694
- path (str): File system path
695
"""
696
697
def setPath(self, path):
698
"""Set file system path."""
699
700
def path(self):
701
"""Get file system path."""
702
703
def fileName(self):
704
"""Get file name without path."""
705
706
def isDir(self):
707
"""Check if item represents directory."""
708
709
def isFile(self):
710
"""Check if item represents file."""
711
712
def size(self):
713
"""Get file size."""
714
715
def lastModified(self):
716
"""Get last modified timestamp."""
717
```
718
719
## Usage Examples
720
721
### Simple Table with Custom Model
722
723
```python
724
import TermTk as ttk
725
726
class CustomTableModel(ttk.TTkAbstractTableModel):
727
def __init__(self, data):
728
super().__init__()
729
self._data = data
730
self._headers = ['Name', 'Age', 'City']
731
732
def rowCount(self, parent=None):
733
return len(self._data)
734
735
def columnCount(self, parent=None):
736
return len(self._headers)
737
738
def data(self, index, role=None):
739
if index.isValid():
740
return self._data[index.row()][index.column()]
741
return None
742
743
def headerData(self, section, orientation, role=None):
744
if orientation == ttk.TTkConstant.Horizontal:
745
return self._headers[section]
746
return str(section + 1)
747
748
# Sample data
749
data = [
750
['Alice', '25', 'New York'],
751
['Bob', '30', 'Los Angeles'],
752
['Charlie', '35', 'Chicago'],
753
['Diana', '28', 'Miami']
754
]
755
756
root = ttk.TTk()
757
container = ttk.TTkContainer(parent=root)
758
759
# Create table with custom model
760
model = CustomTableModel(data)
761
table = ttk.TTkTable(parent=container)
762
table.setModel(model)
763
764
# Handle selection
765
@ttk.pyTTkSlot(ttk.TTkModelIndex)
766
def cell_clicked(index):
767
value = model.data(index)
768
print(f"Clicked: {value} at ({index.row()}, {index.column()})")
769
770
table.clicked.connect(cell_clicked)
771
772
root.mainloop()
773
```
774
775
### Tree Widget with Custom Items
776
777
```python
778
import TermTk as ttk
779
780
root = ttk.TTk()
781
container = ttk.TTkContainer(parent=root)
782
783
# Create tree widget
784
tree = ttk.TTkTreeWidget(parent=container)
785
tree.setHeaderLabels(['Item', 'Type', 'Value'])
786
787
# Create tree structure
788
root_item = tree.invisibleRootItem()
789
790
# Add categories
791
ui_category = ttk.TTkTreeWidgetItem(root_item, ['UI Components', 'Category', ''])
792
data_category = ttk.TTkTreeWidgetItem(root_item, ['Data Models', 'Category', ''])
793
794
# Add UI components
795
button_item = ttk.TTkTreeWidgetItem(ui_category, ['Button', 'Widget', 'Interactive'])
796
label_item = ttk.TTkTreeWidgetItem(ui_category, ['Label', 'Widget', 'Display'])
797
input_item = ttk.TTkTreeWidgetItem(ui_category, ['LineEdit', 'Widget', 'Input'])
798
799
# Add data models
800
table_model = ttk.TTkTreeWidgetItem(data_category, ['Table Model', 'Model', 'Tabular'])
801
tree_model = ttk.TTkTreeWidgetItem(data_category, ['Tree Model', 'Model', 'Hierarchical'])
802
803
# Expand categories
804
ui_category.setExpanded(True)
805
data_category.setExpanded(True)
806
807
# Handle item selection
808
@ttk.pyTTkSlot(ttk.TTkTreeWidgetItem)
809
def item_selected(item):
810
print(f"Selected: {item.text(0)} - {item.text(1)}")
811
812
tree.currentItemChanged.connect(item_selected)
813
814
root.mainloop()
815
```
816
817
### CSV Table Viewer
818
819
```python
820
import TermTk as ttk
821
822
root = ttk.TTk()
823
container = ttk.TTkContainer(parent=root)
824
layout = ttk.TTkVBoxLayout()
825
826
# Create CSV model and table
827
csv_model = ttk.TTkTableModelCSV()
828
table = ttk.TTkTableWidget(parent=container)
829
830
# Load CSV file
831
try:
832
csv_model.loadFromFile('sample_data.csv')
833
table.setModel(csv_model)
834
except FileNotFoundError:
835
# Create sample data if file doesn't exist
836
sample_data = [
837
['Product', 'Price', 'Stock'],
838
['Laptop', '$999', '15'],
839
['Mouse', '$25', '50'],
840
['Keyboard', '$75', '30'],
841
['Monitor', '$299', '8']
842
]
843
844
list_model = ttk.TTkTableModelList(sample_data[1:])
845
list_model.setHeaders(sample_data[0])
846
table.setModel(list_model)
847
848
# Add toolbar
849
toolbar_layout = ttk.TTkHBoxLayout()
850
refresh_btn = ttk.TTkButton(text="Refresh")
851
export_btn = ttk.TTkButton(text="Export CSV")
852
toolbar_layout.addWidget(refresh_btn)
853
toolbar_layout.addWidget(export_btn)
854
toolbar_layout.addStretch(1)
855
856
# Add status bar
857
status = ttk.TTkLabel(text=f"Loaded {table.model().rowCount()} rows")
858
859
# Connect buttons
860
@ttk.pyTTkSlot()
861
def refresh_data():
862
table.model().refresh()
863
status.setText(f"Refreshed - {table.model().rowCount()} rows")
864
865
@ttk.pyTTkSlot()
866
def export_data():
867
# Export logic here
868
status.setText("Data exported")
869
870
refresh_btn.clicked.connect(refresh_data)
871
export_btn.clicked.connect(export_data)
872
873
layout.addLayout(toolbar_layout)
874
layout.addWidget(table)
875
layout.addWidget(status)
876
877
container.setLayout(layout)
878
root.mainloop()
879
```
880
881
### File Tree Browser
882
883
```python
884
import TermTk as ttk
885
import os
886
887
root = ttk.TTk()
888
container = ttk.TTkContainer(parent=root)
889
layout = ttk.TTkVBoxLayout()
890
891
# Create file tree
892
file_tree = ttk.TTkFileTreeWidget(parent=container)
893
file_tree.setRootPath(os.path.expanduser("~")) # Start at home directory
894
895
# Create path bar
896
path_layout = ttk.TTkHBoxLayout()
897
path_label = ttk.TTkLabel(text="Path:")
898
path_edit = ttk.TTkLineEdit(text=file_tree.rootPath())
899
go_btn = ttk.TTkButton(text="Go")
900
901
path_layout.addWidget(path_label)
902
path_layout.addWidget(path_edit, stretch=1)
903
path_layout.addWidget(go_btn)
904
905
# File info panel
906
info_panel = ttk.TTkContainer()
907
info_layout = ttk.TTkVBoxLayout()
908
name_label = ttk.TTkLabel(text="Name: ")
909
type_label = ttk.TTkLabel(text="Type: ")
910
size_label = ttk.TTkLabel(text="Size: ")
911
912
info_layout.addWidget(name_label)
913
info_layout.addWidget(type_label)
914
info_layout.addWidget(size_label)
915
info_layout.addStretch(1)
916
info_panel.setLayout(info_layout)
917
918
# Split layout
919
main_splitter = ttk.TTkSplitter(orientation=ttk.TTkConstant.Horizontal)
920
main_splitter.addWidget(file_tree)
921
main_splitter.addWidget(info_panel)
922
main_splitter.setSizes([70, 30])
923
924
# Handle file selection
925
@ttk.pyTTkSlot(str)
926
def file_selected(path):
927
if os.path.exists(path):
928
name_label.setText(f"Name: {os.path.basename(path)}")
929
930
if os.path.isdir(path):
931
type_label.setText("Type: Directory")
932
size_label.setText("Size: -")
933
else:
934
type_label.setText("Type: File")
935
try:
936
size = os.path.getsize(path)
937
size_label.setText(f"Size: {size} bytes")
938
except OSError:
939
size_label.setText("Size: Unknown")
940
941
file_tree.currentPathChanged.connect(file_selected)
942
943
# Handle path navigation
944
@ttk.pyTTkSlot()
945
def navigate_to_path():
946
path = path_edit.text()
947
if os.path.exists(path) and os.path.isdir(path):
948
file_tree.setRootPath(path)
949
path_edit.setText(path)
950
951
go_btn.clicked.connect(navigate_to_path)
952
953
layout.addLayout(path_layout)
954
layout.addWidget(main_splitter)
955
956
container.setLayout(layout)
957
root.mainloop()
958
```