-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2087 lines (1812 loc) · 72.4 KB
/
main.py
File metadata and controls
2087 lines (1812 loc) · 72.4 KB
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
# -*- coding: utf-8 -*-
"""
离线 JSON 格式化工具
功能:JSON 美化、排序、复制、清空、验证
作者:wangjunqi
版本:1.0
"""
import sys
import json
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
from xml.parsers.expat import ExpatError
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QTextEdit, QPushButton, QLabel, QMessageBox, QSplitter,
QFrame, QStatusBar, QTabWidget, QSpinBox,
QFormLayout, QGroupBox, QLineEdit, QCheckBox, QShortcut,
QTreeWidget, QTreeWidgetItem, QHeaderView, QAbstractItemView,
QComboBox
)
from PyQt5.QtCore import Qt, QTimer, QSettings
from PyQt5.QtGui import QFont, QKeySequence, QTextCursor, QTextCharFormat, QColor, QTextDocument
class JSONTreeWidget(QTreeWidget):
"""
自定义JSON树形视图组件
"""
def __init__(self, parent=None):
super().__init__(parent)
self.setup_tree()
def setup_tree(self):
"""
设置树形视图的基本属性
"""
# 设置列标题
self.setHeaderLabels(["键/索引", "值", "类型"])
# 设置列宽
header = self.header()
header.setStretchLastSection(False)
header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.Stretch)
header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
# 设置选择模式
self.setSelectionMode(QAbstractItemView.SingleSelection)
# 设置样式
self.setStyleSheet("""
QTreeWidget {
border: 2px solid #bdc3c7;
border-radius: 5px;
background-color: white;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
font-size: 24px;
alternate-background-color: #f8f9fa;
}
QTreeWidget::item {
padding: 6px;
border-bottom: 1px solid #ecf0f1;
height: 24px;
}
QTreeWidget::item:selected {
background-color: #3498db;
color: white;
}
QTreeWidget::item:hover {
background-color: #e8f4fd;
}
QTreeWidget::branch:has-children:!has-siblings:closed,
QTreeWidget::branch:closed:has-children:has-siblings {
border-image: none;
image: none;
background-color: #27ae60;
width: 18px;
height: 18px;
border-radius: 9px;
margin: 1px;
border: 2px solid #2ecc71;
}
QTreeWidget::branch:open:has-children:!has-siblings,
QTreeWidget::branch:open:has-children:has-siblings {
border-image: none;
image: none;
background-color: #e74c3c;
width: 18px;
height: 18px;
border-radius: 9px;
margin: 1px;
border: 2px solid #c0392b;
}
QTreeWidget::branch:has-children:!has-siblings:closed:hover,
QTreeWidget::branch:closed:has-children:has-siblings:hover {
background-color: #229954;
border: 2px solid #27ae60;
}
QTreeWidget::branch:open:has-children:!has-siblings:hover,
QTreeWidget::branch:open:has-children:has-siblings:hover {
background-color: #cb4335;
border: 2px solid #e74c3c;
}
""")
# 启用交替行颜色
self.setAlternatingRowColors(True)
# 设置根节点装饰
self.setRootIsDecorated(True)
# 设置动画效果
self.setAnimated(True)
def populate_tree(self, json_data):
"""
填充树形视图数据
"""
self.clear()
if json_data is None:
return
# 创建根节点
if isinstance(json_data, dict):
root_item = QTreeWidgetItem(["JSON Object", f"{len(json_data)} 项", "Object"])
self.addTopLevelItem(root_item)
self._add_dict_items(root_item, json_data)
elif isinstance(json_data, list):
root_item = QTreeWidgetItem(["JSON Array", f"{len(json_data)} 项", "Array"])
self.addTopLevelItem(root_item)
self._add_list_items(root_item, json_data)
else:
# 单个值
root_item = QTreeWidgetItem(["JSON Value", str(json_data), type(json_data).__name__])
self.addTopLevelItem(root_item)
# 展开根节点
self.expandToDepth(0)
def _add_dict_items(self, parent_item, data_dict):
"""
添加字典项到树中
"""
for key, value in data_dict.items():
if isinstance(value, dict):
item = QTreeWidgetItem([str(key), f"{len(value)} 项", "Object"])
parent_item.addChild(item)
self._add_dict_items(item, value)
elif isinstance(value, list):
item = QTreeWidgetItem([str(key), f"{len(value)} 项", "Array"])
parent_item.addChild(item)
self._add_list_items(item, value)
else:
# 处理值的显示
value_str = self._format_value(value)
value_type = type(value).__name__
item = QTreeWidgetItem([str(key), value_str, value_type])
parent_item.addChild(item)
def _add_list_items(self, parent_item, data_list):
"""
添加列表项到树中
"""
for index, value in enumerate(data_list):
if isinstance(value, dict):
item = QTreeWidgetItem([f"[{index}]", f"{len(value)} 项", "Object"])
parent_item.addChild(item)
self._add_dict_items(item, value)
elif isinstance(value, list):
item = QTreeWidgetItem([f"[{index}]", f"{len(value)} 项", "Array"])
parent_item.addChild(item)
self._add_list_items(item, value)
else:
# 处理值的显示
value_str = self._format_value(value)
value_type = type(value).__name__
item = QTreeWidgetItem([f"[{index}]", value_str, value_type])
parent_item.addChild(item)
def _format_value(self, value):
"""
格式化值的显示
"""
if value is None:
return "null"
elif isinstance(value, bool):
return "true" if value else "false"
elif isinstance(value, str):
# 限制字符串长度显示
if len(value) > 100:
return f'"{value[:97]}..."'
return f'"{value}"'
else:
return str(value)
def get_selected_path(self):
"""
获取选中项的路径
"""
current_item = self.currentItem()
if not current_item:
return []
path = []
item = current_item
while item and item.parent():
path.insert(0, item.text(0))
item = item.parent()
return path
class XMLTreeWidget(QTreeWidget):
"""
自定义XML树形视图组件
"""
def __init__(self, parent=None):
super().__init__(parent)
self.setup_tree()
def setup_tree(self):
"""
设置树形视图的基本属性
"""
# 设置列标题
self.setHeaderLabels(["元素/属性", "值", "类型"])
# 设置列宽
header = self.header()
header.setStretchLastSection(False)
header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.Stretch)
header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
# 设置选择模式
self.setSelectionMode(QAbstractItemView.SingleSelection)
# 设置样式(与JSON树形视图相同)
self.setStyleSheet("""
QTreeWidget {
border: 2px solid #bdc3c7;
border-radius: 5px;
background-color: white;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
font-size: 24px;
alternate-background-color: #f8f9fa;
}
QTreeWidget::item {
padding: 6px;
border-bottom: 1px solid #ecf0f1;
height: 24px;
}
QTreeWidget::item:selected {
background-color: #3498db;
color: white;
}
QTreeWidget::item:hover {
background-color: #e8f4fd;
}
QTreeWidget::branch:has-children:!has-siblings:closed,
QTreeWidget::branch:closed:has-children:has-siblings {
border-image: none;
image: none;
background-color: #27ae60;
width: 18px;
height: 18px;
border-radius: 9px;
margin: 1px;
border: 2px solid #2ecc71;
}
QTreeWidget::branch:open:has-children:!has-siblings,
QTreeWidget::branch:open:has-children:has-siblings {
border-image: none;
image: none;
background-color: #e74c3c;
width: 18px;
height: 18px;
border-radius: 9px;
margin: 1px;
border: 2px solid #c0392b;
}
QTreeWidget::branch:has-children:!has-siblings:closed:hover,
QTreeWidget::branch:closed:has-children:has-siblings:hover {
background-color: #229954;
border: 2px solid #27ae60;
}
QTreeWidget::branch:open:has-children:!has-siblings:hover,
QTreeWidget::branch:open:has-children:has-siblings:hover {
background-color: #cb4335;
border: 2px solid #e74c3c;
}
""")
# 启用交替行颜色
self.setAlternatingRowColors(True)
# 设置根节点装饰
self.setRootIsDecorated(True)
# 设置动画效果
self.setAnimated(True)
def populate_tree(self, xml_root):
"""
填充XML树形视图数据
"""
self.clear()
if xml_root is None:
return
# 创建根节点
root_item = QTreeWidgetItem([xml_root.tag, xml_root.text or "", "Element"])
self.addTopLevelItem(root_item)
# 添加根元素的属性
if xml_root.attrib:
for attr_name, attr_value in xml_root.attrib.items():
attr_item = QTreeWidgetItem([f"@{attr_name}", attr_value, "Attribute"])
root_item.addChild(attr_item)
# 递归添加子元素
self._add_xml_elements(root_item, xml_root)
# 展开根节点
self.expandToDepth(0)
def _add_xml_elements(self, parent_item, xml_element):
"""
递归添加XML元素到树中
"""
for child in xml_element:
# 创建子元素节点
child_text = child.text.strip() if child.text else ""
child_item = QTreeWidgetItem([child.tag, child_text, "Element"])
parent_item.addChild(child_item)
# 添加子元素的属性
if child.attrib:
for attr_name, attr_value in child.attrib.items():
attr_item = QTreeWidgetItem([f"@{attr_name}", attr_value, "Attribute"])
child_item.addChild(attr_item)
# 递归处理子元素的子元素
if len(child) > 0:
self._add_xml_elements(child_item, child)
def get_selected_path(self):
"""
获取选中项的路径
"""
current_item = self.currentItem()
if not current_item:
return []
path = []
item = current_item
while item and item.parent():
path.insert(0, item.text(0))
item = item.parent()
return path
class JSONFormatterApp(QMainWindow):
"""
JSON 格式化工具主窗口类
"""
def __init__(self):
"""
初始化主窗口
"""
super().__init__()
# 初始化设置
self.settings = QSettings('JSONFormatter', 'FontSettings')
self.current_text_font_size = self.settings.value('text_font_size', 12, type=int) # 文本编辑器字体
self.current_ui_font_size = self.settings.value('ui_font_size', 14, type=int) # UI元素字体
self.temp_ui_font_size = self.current_ui_font_size # 临时UI字体大小,用于保存前的预览
# 当前格式类型(JSON或XML)
self.current_format = 'JSON'
# 初始化搜索相关变量
self.input_search_widget = None
self.output_search_widget = None
self.input_replace_widget = None
self.output_replace_widget = None
self.current_search_text = ""
self.last_search_position = 0
self.search_results = []
self.current_result_index = -1
# 初始化JSON验证相关变量
self.json_error_format = QTextCharFormat()
self.json_error_format.setBackground(QColor(255, 200, 200)) # 浅红色背景
self.json_normal_format = QTextCharFormat()
self.json_normal_format.setBackground(QColor(255, 255, 255)) # 白色背景
# 移除实时验证相关变量
# self.validation_timer = QTimer()
# self.validation_timer.setSingleShot(True)
# self.validation_timer.timeout.connect(self.validate_json_input)
# self.last_json_error = None
self.init_ui()
self.setup_connections()
self.setup_shortcuts()
self.apply_font_size()
def init_ui(self):
"""
初始化用户界面
"""
# 设置窗口基本属性
self.setWindowTitle('离线 JSON/XML 格式化工具 v1.0')
self.setGeometry(100, 100, 1200, 800)
self.setMinimumSize(800, 600)
# 创建中央部件
central_widget = QWidget()
self.setCentralWidget(central_widget)
# 创建主布局
main_layout = QVBoxLayout(central_widget)
main_layout.setContentsMargins(10, 10, 10, 10)
main_layout.setSpacing(10)
# 创建标签页控件
self.tab_widget = QTabWidget()
main_layout.addWidget(self.tab_widget)
# 创建主功能标签页
main_tab = QWidget()
self.tab_widget.addTab(main_tab, "格式化工具")
# 创建选项标签页
options_tab = QWidget()
self.tab_widget.addTab(options_tab, "选项设置")
# 设置主功能标签页布局
main_tab_layout = QVBoxLayout(main_tab)
main_tab_layout.setContentsMargins(10, 10, 10, 10)
main_tab_layout.setSpacing(10)
# 创建标题和格式选择区域
title_format_layout = QHBoxLayout()
# 创建简化的标题标签(减少占用空间)
self.title_label = QLabel('格式化工具')
self.title_label.setAlignment(Qt.AlignCenter)
self.title_label.setStyleSheet("""
QLabel {
font-size: 14px;
font-weight: bold;
color: #2c3e50;
padding: 5px;
background-color: #ecf0f1;
border-radius: 3px;
margin-bottom: 5px;
}
""")
title_format_layout.addWidget(self.title_label)
# 添加格式选择下拉框
format_label = QLabel('格式类型:')
format_label.setStyleSheet("""
QLabel {
font-size: 16px;
font-weight: bold;
color: #2c3e50;
padding: 5px;
}
""")
title_format_layout.addWidget(format_label)
self.format_combo = QComboBox()
self.format_combo.addItems(['JSON', 'XML'])
self.format_combo.setCurrentText('JSON')
self.format_combo.setStyleSheet("""
QComboBox {
padding: 5px;
border: 1px solid #bdc3c7;
border-radius: 3px;
background-color: white;
min-width: 80px;
}
QComboBox:hover {
border-color: #3498db;
}
QComboBox::drop-down {
border: none;
}
QComboBox::down-arrow {
image: none;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #2c3e50;
margin-right: 5px;
}
""")
self.format_combo.currentTextChanged.connect(self.on_format_changed)
title_format_layout.addWidget(self.format_combo)
title_format_layout.addStretch() # 添加弹性空间
main_tab_layout.addLayout(title_format_layout)
# 创建文本区域布局(增加拉伸因子,占用更多空间)
text_layout = self.create_text_area()
main_tab_layout.addLayout(text_layout, 1) # 拉伸因子为1,占用主要空间
# 创建按钮区域(固定大小,不拉伸)
button_layout = self.create_button_area()
main_tab_layout.addLayout(button_layout, 0) # 拉伸因子为0,保持固定大小
# 设置选项标签页
self.setup_options_tab(options_tab)
# 创建状态栏
self.status_bar = QStatusBar()
self.setStatusBar(self.status_bar)
self.status_bar.showMessage('就绪')
# 设置窗口样式
self.setStyleSheet("""
QMainWindow {
background-color: #f8f9fa;
}
QTextEdit {
border: 2px solid #bdc3c7;
border-radius: 5px;
padding: 10px;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
line-height: 1.4;
background-color: white;
}
QTextEdit:focus {
border-color: #3498db;
}
QPushButton {
background-color: #3498db;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
font-size: 14px;
font-weight: bold;
min-width: 100px;
}
QPushButton:hover {
background-color: #2980b9;
}
QPushButton:pressed {
background-color: #21618c;
}
QPushButton:disabled {
background-color: #bdc3c7;
color: #7f8c8d;
}
""")
def create_text_area(self):
"""
创建文本输入输出区域
"""
# 创建水平分割器
splitter = QSplitter(Qt.Horizontal)
# 创建左侧输入区域
left_frame = QFrame()
left_layout = QVBoxLayout(left_frame)
left_layout.setContentsMargins(0, 0, 5, 0)
self.input_label = QLabel(f'输入 {self.current_format}:')
self.input_label.setStyleSheet("""
QLabel {
font-size: 14px;
font-weight: bold;
color: #2c3e50;
margin-bottom: 5px;
}
""")
left_layout.addWidget(self.input_label)
# 创建输入文本框容器(用于嵌入搜索组件)
self.input_container = QFrame()
self.input_container.setStyleSheet("QFrame { border: 1px solid #bdc3c7; }")
input_container_layout = QVBoxLayout(self.input_container)
input_container_layout.setContentsMargins(0, 0, 0, 0)
input_container_layout.setSpacing(0)
self.input_text = QTextEdit()
self.input_text.setPlaceholderText(f'请在此处输入需要格式化的 {self.current_format} 数据...')
self.input_text.setStyleSheet("QTextEdit { border: none; }")
input_container_layout.addWidget(self.input_text)
left_layout.addWidget(self.input_container)
# 创建右侧输出区域
right_frame = QFrame()
right_layout = QVBoxLayout(right_frame)
right_layout.setContentsMargins(5, 0, 0, 0)
self.output_label = QLabel(f'输出 {self.current_format}:')
self.output_label.setStyleSheet("""
QLabel {
font-size: 14px;
font-weight: bold;
color: #2c3e50;
margin-bottom: 5px;
}
""")
right_layout.addWidget(self.output_label)
# 创建输出区域选项卡
self.output_tab_widget = QTabWidget()
self.output_tab_widget.setStyleSheet("""
QTabWidget::pane {
border: 1px solid #bdc3c7;
background-color: white;
}
QTabWidget::tab-bar {
alignment: left;
}
QTabBar::tab {
background-color: #ecf0f1;
padding: 8px 16px;
margin-right: 2px;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
QTabBar::tab:selected {
background-color: #3498db;
color: white;
}
QTabBar::tab:hover {
background-color: #d5dbdb;
}
""")
# 创建文本视图标签页
text_tab = QWidget()
text_tab_layout = QVBoxLayout(text_tab)
text_tab_layout.setContentsMargins(0, 0, 0, 0)
text_tab_layout.setSpacing(0)
# 创建输出文本框容器(用于嵌入搜索组件)
self.output_container = QFrame()
self.output_container.setStyleSheet("QFrame { border: none; }")
output_container_layout = QVBoxLayout(self.output_container)
output_container_layout.setContentsMargins(0, 0, 0, 0)
output_container_layout.setSpacing(0)
self.output_text = QTextEdit()
self.output_text.setReadOnly(True)
self.output_text.setPlaceholderText(f'格式化后的 {self.current_format} 将显示在此处...')
self.output_text.setStyleSheet("QTextEdit { border: none; }")
output_container_layout.addWidget(self.output_text)
text_tab_layout.addWidget(self.output_container)
# 创建树形视图标签页
tree_tab = QWidget()
tree_tab_layout = QVBoxLayout(tree_tab)
tree_tab_layout.setContentsMargins(0, 0, 0, 0)
self.json_tree = JSONTreeWidget()
self.xml_tree = XMLTreeWidget()
# 将两个树形视图都添加到布局中
tree_tab_layout.addWidget(self.json_tree)
tree_tab_layout.addWidget(self.xml_tree)
# 根据当前格式显示对应的树形视图
if self.current_format == 'JSON':
self.json_tree.show()
self.xml_tree.hide()
else:
self.json_tree.hide()
self.xml_tree.show()
# 添加标签页
self.output_tab_widget.addTab(text_tab, "📄 文本视图")
self.output_tab_widget.addTab(tree_tab, "🌳 树形视图")
right_layout.addWidget(self.output_tab_widget)
# 添加到分割器
splitter.addWidget(left_frame)
splitter.addWidget(right_frame)
splitter.setSizes([600, 600]) # 设置初始比例
# 创建布局并添加分割器
layout = QVBoxLayout()
layout.addWidget(splitter)
return layout
def setup_options_tab(self, options_tab):
"""
设置选项标签页
"""
options_layout = QVBoxLayout(options_tab)
options_layout.setContentsMargins(20, 20, 20, 20)
options_layout.setSpacing(15)
# 字体设置组
font_group = QGroupBox("字体设置")
font_layout = QFormLayout(font_group)
# 定义字体大小范围
self.min_font_size = 8
self.max_font_size = 32
# 文本编辑器字体大小设置
self.text_font_size_spinbox = QSpinBox()
self.text_font_size_spinbox.setMinimum(1)
self.text_font_size_spinbox.setMaximum(999)
self.text_font_size_spinbox.setValue(self.current_text_font_size)
self.text_font_size_spinbox.setSuffix(" px")
self.text_font_size_spinbox.valueChanged.connect(self.on_text_font_size_changed)
font_layout.addRow("文本编辑器字体大小:", self.text_font_size_spinbox)
# UI元素字体大小设置
self.ui_font_size_spinbox = QSpinBox()
self.ui_font_size_spinbox.setMinimum(1)
self.ui_font_size_spinbox.setMaximum(999)
self.ui_font_size_spinbox.setValue(self.current_ui_font_size)
self.ui_font_size_spinbox.setSuffix(" px")
self.ui_font_size_spinbox.valueChanged.connect(self.on_ui_font_size_changed)
font_layout.addRow("界面标签字体大小:", self.ui_font_size_spinbox)
# 保存按钮
self.save_font_button = QPushButton("保存字体设置")
self.save_font_button.setStyleSheet("""
QPushButton {
background-color: #007bff;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
font-weight: bold;
}
QPushButton:hover {
background-color: #0056b3;
}
QPushButton:pressed {
background-color: #004085;
}
""")
self.save_font_button.clicked.connect(self.save_font_settings_and_apply)
font_layout.addRow(self.save_font_button)
# 添加说明标签
self.info_label = QLabel(
"提示:\n• 使用 Ctrl + 鼠标滚轮 可快速调整文本编辑器字体大小\n• 界面标签字体需要点击保存按钮后生效")
self.info_label.setStyleSheet("""
QLabel {
color: #7f8c8d;
font-size: 14px;
padding: 15px;
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 5px;
line-height: 1.5;
}
""")
font_layout.addRow(self.info_label)
options_layout.addWidget(font_group)
options_layout.addStretch()
def create_button_area(self):
"""
创建按钮区域
"""
button_layout = QHBoxLayout()
button_layout.setSpacing(15)
# 创建按钮(添加中文标签)
self.beautify_btn = QPushButton('🎨 美化格式')
self.beautify_btn.setToolTip('格式化 JSON(美化显示)')
self.sort_btn = QPushButton('🔤 排序格式')
self.sort_btn.setToolTip('按键名排序并格式化 JSON')
self.minify_btn = QPushButton('📦 压缩格式')
self.minify_btn.setToolTip('压缩 JSON 为单行')
self.validate_btn = QPushButton('✅ 验证格式')
self.validate_btn.setToolTip('验证 JSON 格式是否正确')
self.copy_btn = QPushButton('📋 复制结果')
self.copy_btn.setToolTip('复制输出结果到剪贴板')
self.clear_btn = QPushButton('🗑️ 清空内容')
self.clear_btn.setToolTip('清空输入和输出内容')
self.expand_all_btn = QPushButton('📂 展开全部')
self.expand_all_btn.setToolTip('展开树形视图中的所有节点')
self.collapse_all_btn = QPushButton('📁 折叠全部')
self.collapse_all_btn.setToolTip('折叠树形视图中的所有节点')
# 设置按钮样式
buttons = [self.beautify_btn, self.sort_btn, self.minify_btn,
self.validate_btn, self.copy_btn, self.expand_all_btn,
self.collapse_all_btn, self.clear_btn]
for i, btn in enumerate(buttons):
if i == len(buttons) - 1: # 清空按钮使用不同颜色
btn.setStyleSheet("""
QPushButton {
background-color: #e74c3c;
}
QPushButton:hover {
background-color: #c0392b;
}
QPushButton:pressed {
background-color: #a93226;
}
""")
elif i == len(buttons) - 3 or i == len(buttons) - 2: # 展开/折叠按钮使用绿色
btn.setStyleSheet("""
QPushButton {
background-color: #27ae60;
}
QPushButton:hover {
background-color: #229954;
}
QPushButton:pressed {
background-color: #1e8449;
}
""")
button_layout.addWidget(btn)
# 添加弹性空间
button_layout.addStretch()
return button_layout
def setup_connections(self):
"""
设置信号连接
"""
self.beautify_btn.clicked.connect(self.beautify_format)
self.sort_btn.clicked.connect(self.sort_format)
self.minify_btn.clicked.connect(self.minify_format)
self.validate_btn.clicked.connect(self.validate_format)
self.copy_btn.clicked.connect(self.copy_output)
self.expand_all_btn.clicked.connect(self.expand_all_tree)
self.collapse_all_btn.clicked.connect(self.collapse_all_tree)
self.clear_btn.clicked.connect(self.clear_all)
# 为文本编辑器安装事件过滤器以处理滚轮事件
self.input_text.installEventFilter(self)
self.output_text.installEventFilter(self)
# 移除实时JSON验证连接
# self.input_text.textChanged.connect(self.on_input_text_changed)
def setup_shortcuts(self):
"""
设置快捷键
"""
# Ctrl+F 搜索快捷键
self.search_shortcut = QShortcut(QKeySequence("Ctrl+F"), self)
self.search_shortcut.activated.connect(self.show_search_dialog)
# Ctrl+R 搜索替换快捷键
self.replace_shortcut = QShortcut(QKeySequence("Ctrl+R"), self)
self.replace_shortcut.activated.connect(self.show_replace_dialog)
def eventFilter(self, obj, event):
"""
事件过滤器,处理Ctrl+滚轮调整字体大小
"""
if (obj == self.input_text or obj == self.output_text) and event.type() == event.Wheel:
if event.modifiers() == Qt.ControlModifier:
# Ctrl + 滚轮只调整文本编辑器字体大小
delta = event.angleDelta().y()
if delta > 0: # 向上滚动,增大字体
self.increase_text_font_size()
# 添加状态栏提示,帮助用户确认字体变化
self.status_bar.showMessage(f'字体大小已调整为: {self.current_text_font_size}px', 2000)
else: # 向下滚动,减小字体
self.decrease_text_font_size()
# 添加状态栏提示,帮助用户确认字体变化
self.status_bar.showMessage(f'字体大小已调整为: {self.current_text_font_size}px', 2000)
return True # 事件已处理
return super().eventFilter(obj, event)
def on_text_font_size_changed(self, size):
"""
文本编辑器字体大小改变时的处理(立即生效)
"""
self.current_text_font_size = size
self.apply_text_font_size()
self.save_text_font_settings()
self.status_bar.showMessage(f"文本编辑器字体大小已调整为 {size}px", 2000)
def on_ui_font_size_changed(self, size):
"""
UI元素字体大小改变时的处理(仅更新临时值,需要保存后生效)
"""
self.temp_ui_font_size = size
self.status_bar.showMessage(f"界面标签字体大小设置为 {size}px(点击保存按钮生效)", 2000)
def increase_text_font_size(self):
"""
增大文本编辑器字体大小
"""
if self.current_text_font_size < 999:
self.current_text_font_size += 1
self.text_font_size_spinbox.setValue(self.current_text_font_size)
def decrease_text_font_size(self):
"""
减小文本编辑器字体大小
"""
if self.current_text_font_size > 1:
self.current_text_font_size -= 1
self.text_font_size_spinbox.setValue(self.current_text_font_size)
def increase_all_font_size(self):
"""
增大所有字体大小
"""
if self.current_text_font_size < self.max_font_size:
self.current_text_font_size += 1
self.text_font_size_spinbox.setValue(self.current_text_font_size)
if self.current_ui_font_size < self.max_font_size:
self.current_ui_font_size += 1
self.ui_font_size_spinbox.setValue(self.current_ui_font_size)
def decrease_all_font_size(self):
"""
减小所有字体大小
"""
if self.current_text_font_size > self.min_font_size:
self.current_text_font_size -= 1
self.text_font_size_spinbox.setValue(self.current_text_font_size)
if self.current_ui_font_size > self.min_font_size:
self.current_ui_font_size -= 1
self.ui_font_size_spinbox.setValue(self.current_ui_font_size)
def apply_text_font_size(self):
"""
应用字体大小到文本编辑器
"""
font = QFont('Consolas', self.current_text_font_size)
if hasattr(self, 'input_text'):
self.input_text.setFont(font)
if hasattr(self, 'output_text'):
self.output_text.setFont(font)
def apply_ui_font_size(self):
"""
应用字体大小到UI元素(包括选项设置页面内的元素)
"""
# 更新标题标签字体
if hasattr(self, 'title_label'):
self.title_label.setStyleSheet(f"""
QLabel {{
font-size: {self.current_ui_font_size}px;
font-weight: bold;
color: #2c3e50;
padding: 5px;
background-color: #ecf0f1;
border-radius: 3px;
margin-bottom: 5px;
}}
""")
# 更新输入输出标签字体
if hasattr(self, 'input_label'):
self.input_label.setStyleSheet(f"""
QLabel {{
font-size: {self.current_ui_font_size}px;
font-weight: bold;
color: #2c3e50;
margin-bottom: 5px;
}}
""")
if hasattr(self, 'output_label'):
self.output_label.setStyleSheet(f"""
QLabel {{
font-size: {self.current_ui_font_size}px;
font-weight: bold;
color: #2c3e50;
margin-bottom: 5px;
}}