-
Notifications
You must be signed in to change notification settings - Fork 3
/
pyside6-assistant.py
1885 lines (1558 loc) · 73.2 KB
/
pyside6-assistant.py
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# pyside6-assistant.py
#
# Ian Stewart - ©CC0
DATE = "2022-10-07"
#
# TODO: Add zoom to textedit / Pyside Information - Strange it doesn't work?
#
# Installations to get some example programs to run...
# $ pip install matplotlib
# $ pip install opencv-python # import cv2
# $ pip install numpy
# $ pip install PyOpenGL
# $ pip install pandas
# $ pip install scipy
# $ pip install matplotlib opencv-python nump PyOpenGL pandas scipy
import sys
import time
import contextlib
from io import StringIO
from pathlib import Path, PurePath, PosixPath
from pygments import formatter, highlight
from pygments.lexers import PythonLexer
from pygments.formatters.html import HtmlFormatter
from pygments.styles import get_style_by_name
from subprocess import run
error_stop = False
try:
import PySide6.Qt3DAnimation as Qt3DAnimation
import PySide6.Qt3DCore as Qt3DCore
import PySide6.Qt3DExtras as Qt3DExtras
import PySide6.Qt3DInput as Qt3DInput
import PySide6.Qt3DLogic as Qt3DLogic
import PySide6.Qt3DRender as Qt3DRender
import PySide6.QtBluetooth as QtBluetooth
import PySide6.QtCharts as QtCharts
import PySide6.QtConcurrent as QtConcurrent
import PySide6.QtCore as QtCore
import PySide6.QtDataVisualization as QtDataVisualization
import PySide6.QtDBus as QtDBus
import PySide6.QtDesigner as QtDesigner
import PySide6.QtGui as QtGui
import PySide6.QtHelp as QtHelp
import PySide6.QtMultimedia as QtMultimedia
import PySide6.QtMultimediaWidgets as QtMultimediaWidgets
import PySide6.QtNetwork as QtNetwork
import PySide6.QtNetworkAuth as QtNetworkAuth
import PySide6.QtNfc as QtNfc
import PySide6.QtOpenGL as QtOpenGL
import PySide6.QtOpenGLWidgets as QtOpenGLWidgets
import PySide6.QtPositioning as QtPositioning
import PySide6.QtPrintSupport as QtPrintSupport
import PySide6.QtQml as QtQml
import PySide6.QtQuick as QtQuick
import PySide6.QtQuick3D as QtQuick3D
import PySide6.QtQuickControls2 as QtQuickControls2
import PySide6.QtQuickWidgets as QtQuickWidgets
import PySide6.QtRemoteObjects as QtRemoteObjects
import PySide6.QtScxml as QtScxml
import PySide6.QtSensors as QtSensors
import PySide6.QtSerialPort as QtSerialPort
import PySide6.QtSql as QtSql
import PySide6.QtStateMachine as QtStateMachine
import PySide6.QtSvg as QtSvg
import PySide6.QtSvgWidgets as QtSvgWidgets
import PySide6.QtTest as QtTest
import PySide6.QtUiTools as QtUiTools
import PySide6.QtWebChannel as QtWebChannel
import PySide6.QtWebEngineCore as QtWebEngineCore
import PySide6.QtWebEngineQuick as QtWebEngineQuick
import PySide6.QtWebEngineWidgets as QtWebEngineWidgets
import PySide6.QtWebSockets as QtWebSockets
import PySide6.QtWidgets as QtWidgets
import PySide6.QtXml as QtXml
except ModuleNotFoundError as e:
print(e)
error_stop = True
# version
VERSION = DATE
PYTHON_VERSION = sys.version.split(" ")[0]
# Qt version
QT_VERSION = "{}".format(QtCore.qVersion())
# Provide the column header with a heading.
HEADING = 'PySide6 Modules'
# Welcome message
WELCOME = """
Welcome to PySide6 Assistant.
Version:{}
Python:{}
Qt Version:{}
App:{}
Select a Help Category and then an item within the category.
""".format(VERSION, PYTHON_VERSION, QT_VERSION, sys.argv[0])
# Programs to be excluded from examples tree as they do not run.
BAD_LIST = [
"/axcontainer/axviewer/axviewer.py", # QAxContainer module is a Windows-only extension.
"/bluetooth/btscanner/main.py", # QtBluetooth requires at least BlueZ version 5.
"/macextras/macpasteboardmime/macpasteboardmime.py", # Only runs on macOS
]
class MainWindow(QtWidgets.QMainWindow):
"""
Main Window setup.
"""
#def __init__(self, *args, **kwargs):
# super(MainWindow, self).__init__(*args, **kwargs)
def __init__(self, dictionary, listing, code_dict, example_list, example_path) -> None:
super().__init__()
# Main Window setup...
self.setWindowTitle("PySide6 Assistant")
self.setWindowIconText("PySide6")
# Add QT icon to System Tray Display.
pixmapi = getattr(QtWidgets.QStyle.StandardPixmap, "SP_TitleBarMenuButton")
icon = self.style().standardIcon(pixmapi)
self.setWindowIcon(icon)
self.resize(1400,800)
# Split Main Window horizontally
splitter_h = QtWidgets.QSplitter()
splitter_h.setOrientation(QtCore.Qt.Orientation.Horizontal)
# splitter_h horizontal is attached to the MainWindow
self.setCentralWidget(splitter_h)
# splitter_v vertical panel in the rhs horizontal panel.
splitter_v = QtWidgets.QSplitter()
splitter_v.setOrientation(QtCore.Qt.Orientation.Vertical)
# Create the text edit for the 1st tab in the splitter_h
self.textedit = QtWidgets.QTextEdit()
self.textedit.setStyleSheet("""
font: 12pt Monospace;
border-width: 1px;
""") # margin: 5px;
self.textedit.setText("")
self.textedit.setText("This is in the textedit tab. for Pyside6 Info.")
# TODO: Strange doesn't work
# Provide keyboard shortcut zooming of the textedit.
# Conflicts with web-browser zooming if + and - are used. Use Ctrl i and o
QtGui.QShortcut("Ctrl+i", self, activated=lambda: self.textedit.zoomIn())
QtGui.QShortcut("Ctrl+o", self, activated=lambda: self.textedit.zoomOut())
##### Create the Browser for displaying the code in html form #####
self.code_browser = QtWebEngineWidgets.QWebEngineView()
self.code_browser.setPage(CustomWebEnginePage(self))
self.code_browser.setZoomFactor(1.2)
# Provide keyboard shortcut zoom-in -out -reset of the WebEngineView.
QtGui.QShortcut("Ctrl++", self, activated=lambda:
self.code_browser.setZoomFactor(self.code_browser.zoomFactor() + 0.2))
QtGui.QShortcut("Ctrl+-", self, activated=lambda:
self.code_browser.setZoomFactor(self.code_browser.zoomFactor() - 0.2))
QtGui.QShortcut("Ctrl+0", self, activated=lambda: self.code_browser.setZoomFactor(1))
# Quit. Shortcut.
QtGui.QShortcut("Ctrl+q", self, activated=lambda: self.close())
# Test load data to the Browser
#url = QtCore.QUrl.fromLocalFile(Path.cwd().as_posix() + "/test_pig_1.html")
#print(url) # PySide6.QtCore.QUrl('file:///home/ian/pyside6/test_pig_1.html')
#self.code_browser.load(url)
self.code_browser.setHtml("Use the search to locate desired string in python code.")
# Add tabs to the left horizontal splitter panel.
self.tabs = QtWidgets.QTabWidget()
self.tabs.addTab(self.textedit, "PySide6 Information")
self.tabs.addTab(self.code_browser, "Python Code")
# Provide keyboard shortcut zooming of the textedit.
# Conflicts with web-browser zooming if + and - are used. Use Ctrl i and o
#QtGui.QShortcut("Ctrl+i", self, activated=lambda: self.textedit.zoomIn())
#QtGui.QShortcut("Ctrl+o", self, activated=lambda: self.textedit.zoomOut())
splitter_h.addWidget(self.tabs)
# Add v splitter on rhs of h splitter
splitter_h.addWidget(splitter_v)
##### Inserted from pyside6-help ######
label = QtWidgets.QLabel()
label.setText("Search PySide6...")
splitter_v.addWidget(label)
search_field = QtWidgets.QLineEdit()
search_field.setClearButtonEnabled(True)
search_field.setPlaceholderText("Enter 4+ Characters...")
# Use lambda to pass variables with the call.
search_field.textChanged.connect(lambda x: self.search_changed(x, dictionary, listing))
splitter_v.addWidget(search_field)
self.setStyleSheet("""
margin: 1px;
""")
'''
splitter_v.setStyleSheet("""
border-width: 15px;
border-radius: 4px;
background-color: red;
""") # border-style: outset;
splitter_h.setStyleSheet("""
border-width: 15px;
border-radius: 4px;
""")
'''
self.list_widget = QtWidgets.QListWidget()
self.list_widget.clicked.connect(self.search_list_clicked)
splitter_v.addWidget(self.list_widget)
tree_widget = QtWidgets.QTreeWidget()
splitter_v.addWidget(tree_widget)
tree_widget.clear()
tree_widget.setHeaderLabel(HEADING)
tree_widget.setColumnCount(1)
tree_widget.clicked.connect(self.treewidget_clicked)
self.fill_tree_widget_item(tree_widget.invisibleRootItem(), dictionary)
# Create the examples tree and add it as bottom item on splitter_v
for item in BAD_LIST:
example_list.remove(item)
tree_dict = self.create_example_tree_dict(example_list)
tree_example = QtWidgets.QTreeWidget()
#tree_example = QTreeWidget()
#tree_example.setMinimumHeight(500) #resize(200,500)
splitter_v.addWidget(tree_example)
#tree_example.clear()
tree_example.setHeaderLabel("Run Example Programs")
tree_example.setColumnCount(1)
#tree_example.clicked.connect(self.tree_example_clicked)
tree_example.clicked.connect(lambda x: self.tree_example_clicked(x, example_path))
self.fill_tree_example_item(tree_example.invisibleRootItem(), tree_dict)
#self.setCentralWidget(tree_example)
splitter_h.setStretchFactor(0,4)
splitter_h.setStretchFactor(1,3)
splitter_v.setStretchFactor(0,1)
splitter_v.setStretchFactor(1,1)
splitter_v.setStretchFactor(2,1)
splitter_v.setStretchFactor(3,1)
self.textedit.setText(WELCOME + MESSAGE_1 + MESSAGE_2)
# Statusbar
self.find_text = ""
self.match_position = 0
self.match_total = 0
#True
self.sb = QtWidgets.QStatusBar()
self.setStatusBar(self.sb)
# HBox doesn't work on Status bar.
#hbox = QtWidgets.QHBoxLayout()
#self.sb.addWidget(hbox)
# TypeError: 'PySide6.QtWidgets.QStatusBar.addWidget' called with wrong argument types:
#PySide6.QtWidgets.QStatusBar.addWidget(QHBoxLayout)
self.find = QtWidgets.QLineEdit()
self.find.setClearButtonEnabled(True)
self.find.setPlaceholderText("Find...")
self.find.setStyleSheet("""
width: 150px;
max-width: 160px;
""")
#border-width: 10px;
#padding-bottom: 5px;
#""")
self.find.textChanged.connect(lambda x: self.find_changed(x)) #, dictionary, listing))
self.sb.addWidget(self.find)
sb_up = QtWidgets.QPushButton()
sb_up.clicked.connect(self.sb_up_clicked)
pixmapi = getattr(QtWidgets.QStyle.StandardPixmap, "SP_ArrowUp")
icon = self.style().standardIcon(pixmapi)
sb_up.setIcon(icon)
self.sb.addWidget(sb_up)
sb_down = QtWidgets.QPushButton()
sb_down.clicked.connect(self.sb_down_clicked)
pixmapi = getattr(QtWidgets.QStyle.StandardPixmap, "SP_ArrowDown")
icon = self.style().standardIcon(pixmapi)
sb_down.setIcon(icon)
self.sb.addWidget(sb_down)
self.sb_checkbox = QtWidgets.QCheckBox()
self.sb_checkbox.setText("Case Sensitive")
self.sb_checkbox.clicked.connect(self.sb_match_case_changed)
self.case_sensitive = self.sb_checkbox.isChecked()
self.sb.addWidget(self.sb_checkbox)
self.sb_label = QtWidgets.QLabel()
self.sb_label.setText("{} of {} matches".format(self.match_position,self.match_total))
self.sb.addWidget(self.sb_label)
#self.addWidget(self.sb)
#splitter_v.addWidget(self.sb)
# Display Icons included with PySide6
# https://www.pythonguis.com/faq/built-in-qicons-pyqt/
self.sb_button = QtWidgets.QPushButton()
self.sb_button.setText("Icon View")
#self.sb_button.clicked.connect(self.sb_button_icon_view)
self.sub_window = SubWindow()
self.sb_button.clicked.connect(self.sub_window.show)
self.sb.addWidget(self.sb_button)
# Add a spacer to right justify the Search widgets. Not supported
#spacer = QtWidgets.QSpacerItem(2, 4, QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.MinimumExpanding)
#self.spacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
#self.sb.addWidget(self.spacer)
#TypeError: 'PySide6.QtWidgets.QStatusBar.addWidget' called with wrong argument types:
#PySide6.QtWidgets.QStatusBar.addWidget(QSpacerItem)
# Add a label to pack toward the right:
self.sb_label_2 = QtWidgets.QLabel()
self.sb_label_2.setText("Search in Python code:")
self.sb.addWidget(self.sb_label_2)
##### Search for code examples to list 10 lines of in code tab window. #####
self.search = QtWidgets.QLineEdit()
self.search.setClearButtonEnabled(True)
self.search.setPlaceholderText("Find...")
self.search.setStyleSheet("""
width: 150px;
max-width: 160px;
""")
#border-width: 10px;
#padding-bottom: 5px;
#""")
self.search.textChanged.connect(lambda x: self.search_str_changed(x, code_dict))
#self.search_str.textChanged.connect(lambda x: self.search_str_changed(x, dictionary, listing))
#, dictionary, listing))
self.sb.addWidget(self.search)
# Add a message label to pack toward the right:
self.sb_label_3 = QtWidgets.QLabel()
self.sb_label_3.setText("")
self.sb.addWidget(self.sb_label_3)
##### Functions that are part of the MainWindow #####
##### 3 x Methods for tree examples to run programs
def create_example_tree_dict(self, example_list):
"""
Using example_list, create a dictionary to feed to the Tree Widget
Tree normally has two levels of dictionary and then a list of programs.
E.g. 30 items in top level.
"""
tree_dict = {}
for index, path_file in enumerate(example_list):
path_file_list = path_file.split("/")
# Remove the None field at the begining...
path_file_list.pop(0)
# Get the top-level key
key = path_file_list.pop(0)
# Remove the last item, python filename.
python_file = path_file_list.pop(-1)
# Create the sub-key from the remaining items in the list.
path_file_str = "/".join(path_file_list)
# Commence building the tree_dict. Add the primary keys
if not key in tree_dict:
tree_dict[key] = {}
# Add the sub-keys
if path_file_str not in tree_dict[key]:
tree_dict[key].update({path_file_str:[]})
# Append the list of python files.
tree_dict[key][path_file_str].append(python_file)
# Restore tree_dict to string
#print(tree_dict)
count = 0
for key, value_dict in tree_dict.items():
#print(key, value_dict)
for sub_key, value_list in value_dict.items():
for python_file in value_list:
if sub_key == "":
string = "/" + key + "/" + python_file
else:
string = "/" + key + "/" + sub_key + "/" + python_file
#print(string)
# Checks...
count += 1
#if string not in example_list:
# print("Missing:", string)
#print(count) # 284
return tree_dict
"""
# Check: Restore tree_dict to string
#print(tree_dict)
count = 0
for key, value_dict in tree_dict.items():
#print(key, value_dict)
for sub_key, value_list in value_dict.items():
for item in value_list:
if sub_key == "":
string = "/" + key + "/" + item
else:
string = "/" + key + "/" + sub_key + "/" + item
print(string)
# Checks...
count += 1
if string not in example_list:
print("Missing:", string)
print(count) # 284
"""
def fill_tree_example_item(self, invisible_root_item, dictionary):
for top_key, sub_dict in dictionary.items():
# Dictionaries: 'QDomText': ['EncodingPolicy', 'NodeType', ...'toText']}
parent = QtWidgets.QTreeWidgetItem([str(top_key)])
#parent = QTreeWidgetItem([str(top_key)])
parent.setFlags(parent.flags() & ~ QtCore.Qt.ItemFlag.ItemIsSelectable)
#parent.setFlags(parent.flags() & ~ Qt.ItemFlag.ItemIsSelectable)
# In qt6, .flags() replaced by pyqtEnum(enum) ???
invisible_root_item.addChild(parent)
for sub_key, python_file_list in sub_dict.items():
child = QtWidgets.QTreeWidgetItem([str(sub_key)])
#child = QTreeWidgetItem([str(sub_key)])
child.setFlags(child.flags() & ~ QtCore.Qt.ItemFlag.ItemIsSelectable)
#child.setFlags(child.flags() & ~ Qt.ItemFlag.ItemIsSelectable)
parent.addChild(child)
#print(len(python_file_list))
for method in python_file_list:
# The Python files are defaulted to ItemIsSelectable.
grandchild = QtWidgets.QTreeWidgetItem([str(method)])
#grandchild = QTreeWidgetItem([str(method)])
child.addChild(grandchild)
#print(dictionary[top_key][sub_key])
def tree_example_clicked(self, model_index, example_path):
"""
The parent, child or grand-child has been clicked in QListWidget.
Build a list
"""
#print(model_index)
#print(model_index.flags().value) # 60 parent or 61 child
# Check is ItemIsSelectable based on model_index.flags()
if not model_index.flags() & QtCore.Qt.ItemFlag.ItemIsSelectable:
#if not model_index.flags() & Qt.ItemFlag.ItemIsSelectable:
#print("Item is not selectable")
return
item_list = []
item_list.append(model_index.data())
# Potential for between 1 to 3 levels above.
try:
parent = model_index.parent()
if parent.data():
item_list.insert(0, parent.data())
except:
pass
try:
grandparent = parent.parent()
if grandparent.data():
item_list.insert(0, grandparent.data())
except:
pass
#print(item_list)
item_str = "/" + "/".join(item_list)
#print(item_str)
# Full path and program name
program = example_path + item_str
# Remove the filename form the itemlist
python_file = item_list.pop(-1)
directory = example_path + "/" + "/".join(item_list)
dir_path = Path(directory)
files = dir_path.rglob('*')
# files.sort() # AttributeError: 'generator' object has no attribute 'sort'
# print(type(files)) # <class 'generator'>
# Convert from generator list to normal list.
# Remove __pycache__ related files.
file_list = []
for file in files:
if "__pycache__" not in file.as_posix():
file_list.append(file.as_posix())
file_list.sort()
#print(file_list)
#print(type(file_list))
#print(len(file_list))
# Build the html string of code for displaying by the web_browser.
html_str = ""
for file in file_list:
if file.endswith(".py"):
#print(file)
lexer = PythonLexer()
#style = get_style_by_name('friendly')
#style = get_style_by_name('github-dark')
#style = get_style_by_name('paraiso-dark')
#style = get_style_by_name('tango')
#style = get_style_by_name('native')
#style = get_style_by_name('colorful')
style = get_style_by_name('default')
#style = get_style_by_name('algol')
formatter = HtmlFormatter(full=True, style=style, linenos=True)
with open(file, "r") as fin:
python_code = fin.read()
# Add to html string the path and filename, and the code.
html_str += "<h4 style='color:chartreuse;'>{}</h4>".format(file)
html_str += highlight(python_code, lexer, formatter)
# Add the list of files for this example program.
html_str += "<h4>Files in example directory:</h4>"
html_str += "<p style='color:chartreuse;font-size:12px;'>{}</p>".format(example_path)
for file in file_list:
html_str += "<p style='color:yellow;font-size:12px;'>{}</p>".format(file)
# TODO: The follow 2 lines of code appear to run in reverse order!
# Update the code_browser with the html string.
self.code_browser.setHtml(html_str)
# Use subprocess to run the example program.
run(['python', program])
##### Search #####
def search_str_changed(self, search_str, code_dict):
"""
Search dictionary code for match.
Build a string.
Convert to pigmented html
Display in a seperate window.
"""
#print(search_str)
# Make the search string global. Huh?
self.search_str = search_str
if len(search_str) < 3:
self.sb_label_3.setText("")
return
document = self.search_code_dict(code_dict, search_str)
#print(document)
document_list = document.split("\n")
#print("len(document_list)):", len(document_list), "len(document_list)/12:", (len(document_list)-1)//12)
if (len(document_list)-1)//12 > 100:
# TODO: Add label with search result status
#print("Refine search: {} matches".format((len(document_list)-1)//12))
self.sb_label_3.setText("Refine search: {} matches".format((len(document_list)-1)//12))
return
# Convert the document. to HTML
#print("Search: '{}' has {} matches".format(search_str, (len(document_list)-1)//12))
self.sb_label_3.setText("{} matches".format((len(document_list)-1)//12))
self.convert_search_results_to_html(document)
return
def convert_search_results_to_html(self, document):
"""
Convert the document to html data for displaying in WebEngineView browser.
"""
lexer = PythonLexer()
#style = get_style_by_name('friendly')
#style = get_style_by_name('native')
#style = get_style_by_name('colorful')
style = get_style_by_name('default')
formatter = HtmlFormatter(full=True, style=style, linenos=True,
title="Python Code Examples")
# Create the html, but it will not have correct navigation links to the html files.
document_html_draft = highlight(document, lexer, formatter)
# Edit the html to create the navigation links
document_html = self.add_html_navigation_links(document_html_draft)
self.code_browser.setHtml(document_html)
def add_html_navigation_links(self, draft_html):
prefix = '<a href="file:///'
suffix = '</a>'
draft_html_list = draft_html.split("\n")
final_html_list = []
for line in draft_html_list:
#print(line)
if line.startswith('<span class="c1"># '):
#print(line[:-1])
# <span class="c1"># charts/areachart/areachart.py</span>
# .py needs to be changed to .html
beginning = line.split(" ")[0] + " " + line.split(" ")[1] + " "
link_click = line.split(" ")[2]
link_click, _, _ = link_click.partition("</span>") # link_click.split("</span>")[0]
# .py is changed to .html
link_click = link_click[:-2] + "html"
ending = "</span>"
#print(beginning)
#print(link_click)
#print(ending)
full_path = "/home/ian/pyside6/example_html/"
new_line = beginning + ending + prefix + full_path + link_click + '">' + link_click + "</a>"
#print(new_line)
final_html_list.append(new_line)
else:
final_html_list.append(line)
final_html_str = "\n".join(final_html_list)
return final_html_str
def search_code_dict(self, code_dict, search_string):
"""
Search all code for match of a string.
Display: File name, link to file name, code line, and 5 lines preceeding and after.
Maintain an 11 line buffer 0 to 4 preceeding lines, 5 is focus line, 6 to 10 post lines
"""
global python
document = ""
for file, code_list in code_dict.items():
#print(file)
# Run a 10 line buffer.
buffer_list = []
code_line_total = len(code_list)
#print("code_line_total:", code_line_total)
for index, line in enumerate(code_list):
buffer_list.append(line)
#TODO build this up. start at 5 lines for match in first line.
if index < 9:
continue
if index == 9:
# search lines 0 to 4
for i in range(5):
string = self.search_line(buffer_list, file, search_string, i)
#if index > 9 and index <= code_line_total - 1: # 10 to 35 out of 40
if index > 9 and index < code_line_total: # 10 to 35 out of 40
buffer_list.pop(0) # keep list length at 10
# search line 5th line, index of 4
if index < code_line_total:
string = self.search_line(buffer_list, file, search_string, 4)
# Last search when index has reached max
if index == code_line_total -1: # This is the last loading of the buffer
#print("reach code line total")
# Wind this down
# check the search string in the last 5 lines of the buffer_list
for i in range(5):
buffer_list.pop(0)
string = self.search_line(buffer_list, file, search_string, 4)
if string:
pass
#print(string)
if string:
document += string
"""
# OK with both TextEdit and TextBrowser
python.moveCursor(QtGui.QTextCursor.MoveOperation.End,
QtGui.QTextCursor.MoveMode.MoveAnchor) # Moves cursor to the end OK.
print(python.insertPlainText(string)) #
print("done") # This is quick
# TODO: Pass strinf each time and append QTextEdit - still slow
# Try and Html window. can include links.
"""
#print(document) # pass document to highlighter.
#print(type(python)) # <class 'PySide6.QtWidgets.QTextEdit'>
return document
def search_line(self, buffer_list, file, search_string, focus_line_index):
"""
Build the string of the 10 line code samples.
"""
string = ""
if search_string in buffer_list[focus_line_index]:
#print("Found in line:", focus_line_index, buffer_list[focus_line_index], buffer_list[0], buffer_list[-1], len(buffer_list))
string += ("#" + "="*80 + "\n")
string += ("# " + file + "\n") # + " ~ Searching for: " + search_string + "\n")
for line in buffer_list:
string += line + "\n"
#print(string)
return string
#print(string)
"""
print("="*80)
print(file) # + " ~ Searching for: " + search_string)
print()
for line in buffer_list:
print(line)
"""
##### End of building 11 line string #####
def sb_match_case_changed(self, is_checked):
"""
Case sensitive checkbox default to passing to callback its boolean status.
"""
if is_checked:
self.case_sensitive = True
else:
self.case_sensitive = False
# Call a refresh of the matching statistics.
self.find_changed(self.find_text)
def perform_search(self, find_text, is_case_sensitive=False, is_backward=False):
"""
Perform a search of self.text_edit, dependent on search directiom and if
search is case sensitive.
Return status of the success of the search. Bool.
Notes:
FindBackward = <FindFlag.FindBackward: 1>
FindCaseSensitively = <FindFlag.FindCaseSensitively: 2>
FindWholeWords = <FindFlag.FindWholeWords: 4>
"""
if is_case_sensitive and is_backward:
find_status = self.textedit.find(self.find_text,
QtGui.QTextDocument.FindFlag.FindBackward |
QtGui.QTextDocument.FindFlag.FindCaseSensitively )
elif is_backward: # and case insensitive
find_status = self.textedit.find(self.find_text,
QtGui.QTextDocument.FindFlag.FindBackward)
elif is_case_sensitive: # and search forwards
find_status = self.textedit.find(self.find_text,
QtGui.QTextDocument.FindFlag.FindCaseSensitively )
else: # Case insensitive and search farwards
find_status = self.textedit.find(self.find_text)
return find_status
def sb_up_clicked(self, button):
"""
Callback when clicked on Up Arrow icon in Status Bar search.
"""
self.backward = True
if self.perform_search(self.find_text, self.case_sensitive, self.backward):
self.match_position -= 1
self.sb_label.setText("{} of {} matches".format(self.match_position,
self.match_total))
else:
#print("Not found")
# Wrap around to the start
self.textedit.moveCursor(QtGui.QTextCursor.MoveOperation.End,
QtGui.QTextCursor.MoveMode.MoveAnchor )
#find_status = self.textedit.find(self.find_text)
self.match_position = self.match_total
if self.perform_search(self.find_text, self.case_sensitive, self.backward):
self.sb_label.setText("{} of {} matches".format(self.match_position,
self.match_total))
else:
# NO MATCH EXISTS
self.sb_label.setText("{} of {} matches".format(self.match_position,
self.match_total))
return
def sb_down_clicked(self, button):
"""
Callback when clicked on Down Arrow icon in Status Bar search.
"""
if self.perform_search(self.find_text, self.case_sensitive):
self.match_position += 1
self.sb_label.setText("{} of {} matches".format(self.match_position,
self.match_total))
else:
#print("Not found")
# Wrap around to the start
self.textedit.moveCursor(QtGui.QTextCursor.MoveOperation.Start,
QtGui.QTextCursor.MoveMode.MoveAnchor )
#find_status = self.textedit.find(self.find_text)
self.match_position = 0
if self.perform_search(self.find_text, self.case_sensitive):
self.match_position += 1
self.sb_label.setText("{} of {} matches".format(self.match_position,
self.match_total))
else:
# NO MATCH EXISTS
self.sb_label.setText("{} of {} matches".format(self.match_position,
self.match_total))
return
def find_changed(self, find_text):
"""
Call-back for each time a character is entered in sb_find - QLineEdit
find_text in self.textedit and count total number of matches.
Calls perform_search to advance search to next match.
Establishes: self.match_total, self.match_position, self.find_text
"""
# Make the search string global.
self.find_text = find_text
if len(find_text) < 2:
return
self.match_total = 0
self.match_position = 0
# Move cursor to Start. - Test with KeepAnchor
self.textedit.moveCursor(QtGui.QTextCursor.MoveOperation.Start,
QtGui.QTextCursor.MoveMode.MoveAnchor)
# Count the total number of matches.
#position_list = [] # For testing the matching.
while True:
if self.perform_search(find_text, self.case_sensitive):
self.match_total += 1
#position_list.append(self.textedit.textCursor().position())
else:
# Reached last match at bottom of the text
break
# Return to start / top of text.
self.textedit.moveCursor(QtGui.QTextCursor.MoveOperation.Start,
QtGui.QTextCursor.MoveMode.MoveAnchor)
# Update the matches label. match_position is 0
self.sb_label.setText("{} of {} matches".format(self.match_position,
self.match_total))
#print("Position list:", position_list) # Position list: [160, 294]
# Find first match, going forward from start / top of text.
if self.perform_search(find_text, self.case_sensitive):
self.match_position += 1
# Update the matches label. match_position should be 1
self.sb_label.setText("{} of {} matches".format(self.match_position,
self.match_total))
def search_changed(self, search_text, dictionary, listing):
"""
Callback for when characters are enterd in primary search QLineEdit.
"""
# Passed the dictionary (qt6_dict) and listing (qt6_list)
# Don't do any searches until 4th character is entered.
if len(search_text) <= 3:
return
self.list_widget.clear()
# Case insensitive search.
# Search the listing. If search string contains a "."
if "." in search_text:
for string in listing:
if search_text.lower() in string.lower():
self.list_widget.addItem(string)
# Search in dictionary seperately in modules, classes and methods.
else:
# 1st level search - Modules. (Under PySide6 library)
for module, class_dict in dictionary.items():
if search_text.lower() in module.lower():
self.list_widget.addItem("PySide6." + module)
# 2nd Level search - Classes
for class_name, method_list in class_dict.items():
if search_text.lower() in class_name.lower():
self.list_widget.addItem("PySide6." + module + "." + class_name)
# 3rd level search - Methods
for method in method_list:
if search_text.lower() in method.lower():
self.list_widget.addItem("PySide6." + module + "." +
class_name + "." + method)
def search_list_clicked(self, model_index):
"""
Callback when click on item in QListWidget
"""
item = model_index.data()
item_list = item.split(".")
self.setWindowTitle("PySide6 Help - Selection: {}".format(item))
string_1 = ""
if len(item_list) > 2:
string_1 = "\n\nfrom PySide6.{} import {}\n".format(item_list[1], item_list[2])
# get the help data
string_2 = display_pyside6_help(item_list)
self.textedit.setText(item + string_1 + string_2)
#string = display_pyside6_help(item_list)
#self.textedit.setText(string)
def fill_tree_widget_item(self, invisible_root_item, dictionary):
for top_key, class_dict in dictionary.items():
# Dictionaries: 'QDomText': ['EncodingPolicy', 'NodeType', ...'toText']}
parent = QtWidgets.QTreeWidgetItem([str(top_key)])
#parent.setFlags(parent.flags() & ~ QtCore.Qt.ItemFlag.ItemIsSelectable)
# In qt6, .flags() replaced by pyqtEnum(enum) ???
invisible_root_item.addChild(parent)
for class_name, method_list in class_dict.items():
child = QtWidgets.QTreeWidgetItem([str(class_name)])
#child.setFlags(child.flags() & ~ QtCore.Qt.ItemFlag.ItemIsSelectable)
parent.addChild(child)
#print(len(method_list))
for method in method_list:
grandchild = QtWidgets.QTreeWidgetItem([str(method)])
child.addChild(grandchild)
#print(dictionary[top_key][class_name])
def treewidget_clicked(self, model_index):
"""
The parent, child or grand-child has been clicked in QListWidget.
Build a list
"""
#print(model_index) # PySide6.QtCore.QModelIndex object
#print(model_index.flags().value) # 60 parent or 61 child
# Check is ItemIsSelectable based on model_index.flags()
if not model_index.flags() & QtCore.Qt.ItemFlag.ItemIsSelectable:
#print("Item is not selectable")
return
item_list = []
item_list.append(model_index.data())
# Potential for between 1 to 3 levels above.
try:
parent = model_index.parent()
if parent.data():
item_list.insert(0, parent.data())
except:
pass
try:
grandparent = parent.parent()
if grandparent.data():
item_list.insert(0, grandparent.data())
except:
pass
# Insert the root of the tree
item_list.insert(0, "PySide6")
item_str = ".".join(item_list)
self.setWindowTitle("PySide6 Help - Selection: {}".format(item_str))
string_1 = ""
if len(item_list) > 2:
string_1 = "\n\nfrom PySide6.{} import {}\n".format(item_list[1], item_list[2])
# get the help data
string_2 = display_pyside6_help(item_list)
self.textedit.setText(item_str + string_1 + string_2)
class CustomWebEnginePage(QtWebEngineCore.QWebEnginePage):
"""
Links in the WebEngineView Browser, "code_browser", are to HTML files.
Open a WebEngineView, "html_window", and display the html file.
"""
# Store second window.