-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuiqt0_2_3_5.py
More file actions
2139 lines (1794 loc) · 79.4 KB
/
uiqt0_2_3_5.py
File metadata and controls
2139 lines (1794 loc) · 79.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
import os
import sys
import types
import ctypes
import signal
import inspect
import hashlib
import threading
import traceback
import subprocess
import faulthandler
import importlib.util
from PyQt5 import QtCore, QtGui, QtWidgets
from contextvars import ContextVar
from PyQt5.QtWidgets import QDialog, QTextEdit, QWidget, QLabel, QApplication, QPushButton, QScrollArea, QVBoxLayout, QHBoxLayout, QSplitter
from PyQt5.QtCore import Qt, pyqtBoundSignal, QThread, pyqtSignal, QTimer, QSize, QPropertyAnimation, QEasingCurve, QRect, QParallelAnimationGroup
from PyQt5.QtGui import QFont, QIcon, QPalette, QColor, QFontDatabase
# 打开文件保存崩溃信息
crash_log = open("crash.log", "a")
# 开启 faulthandler
faulthandler.enable(crash_log)
# 某些 Python 版本(>=3.9)支持 register
if hasattr(faulthandler, "register"):
try:
faulthandler.register(signal.SIGSEGV, crash_log)
faulthandler.register(signal.SIGABRT, crash_log)
except Exception as e:
print("Warning: faulthandler.register failed:", e)
# 捕获 Python 层未处理异常
def excepthook(exc_type, exc_value, exc_tb):
print("Uncaught exception:", exc_type.__name__)
traceback.print_exception(exc_type, exc_value, exc_tb, file=sys.stderr)
traceback.print_exception(exc_type, exc_value, exc_tb, file=crash_log)
crash_log.flush()
sys.excepthook = excepthook
# =======================
# DPI 设置(尽可能在 Windows 上启用 per-monitor DPI awareness)
# =======================
# 启用 Qt 高 DPI 模式(推荐)
QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
# ==================================================
# 插件调用上下文
# ==================================================
_current_plugin_ctx = ContextVar("current_plugin_ctx", default=None)
def get_current_plugin_name():
#print(f"Getting current plugin name...")
return _current_plugin_ctx.get()
# 接管 threading.Thread
_original_thread_init = threading.Thread.__init__
def _context_aware_thread_init(self, *args, **kwargs):
plugin_name = get_current_plugin_name()
_original_thread_init(self, *args, **kwargs)
if plugin_name:
original_run = self.run
def run_with_ctx():
token = _current_plugin_ctx.set(plugin_name)
try:
return original_run()
finally:
_current_plugin_ctx.reset(token)
self.run = run_with_ctx
threading.Thread.__init__ = _context_aware_thread_init
# 接管 Qt Signal
_original_signal_connect = pyqtBoundSignal.connect
def _context_aware_signal_connect(self, slot, *args, **kwargs):
plugin_name = get_current_plugin_name()
if not plugin_name:
return _original_signal_connect(self, slot, *args, **kwargs)
def wrapped(*a, **k):
token = _current_plugin_ctx.set(plugin_name)
try:
try:
# 先尝试完整参数调用
return slot(*a, **k)
except TypeError:
# Qt 多给参数时自动降级
return slot()
finally:
_current_plugin_ctx.reset(token)
return _original_signal_connect(self, wrapped, *args, **kwargs)
pyqtBoundSignal.connect = _context_aware_signal_connect
# 接管 QTimer.singleShot
_original_single_shot = QtCore.QTimer.singleShot
def _context_aware_single_shot(*args):
plugin_name = get_current_plugin_name()
if not plugin_name:
return _original_single_shot(*args)
if len(args) == 2 and callable(args[1]):
msec, func = args
def wrapped():
token = _current_plugin_ctx.set(plugin_name)
try:
func()
finally:
_current_plugin_ctx.reset(token)
return _original_single_shot(msec, wrapped)
if len(args) == 3:
msec, receiver, slot = args
def wrapped():
token = _current_plugin_ctx.set(plugin_name)
try:
slot()
finally:
_current_plugin_ctx.reset(token)
return _original_single_shot(msec, receiver, wrapped)
raise TypeError("QTimer.singleShot 参数不合法")
QtCore.QTimer.singleShot = _context_aware_single_shot
# 接管 QTimer.timeout.connect (已删除)
"""_original_timeout_connect = QtCore.QTimer.timeout.fget
def _context_aware_timeout(self):
signal = _original_timeout_connect(self)
original_connect = signal.connect
def connect(slot):
ctx = copy_context()
def wrapped(*a, **k):
return ctx.run(slot, *a, **k)
return original_connect(wrapped)
signal.connect = connect
return signal
QtCore.QTimer.timeout = property(_context_aware_timeout)"""
def resource_path(relative_path):
"""获取打包后资源路径(兼容 PyInstaller)"""
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
# ------------------------
# 弹窗显示安装进度
# ------------------------
class InstallWindow(QDialog):
append_text = pyqtSignal(str)
update_dep = pyqtSignal(str)
def __init__(self):
super().__init__()
self.setWindowTitle("依赖安装")
self.resize(250, 150)
self.setWindowModality(Qt.ApplicationModal) # 模态,阻塞主UI
layout = QVBoxLayout()
self.label = QLabel("准备安装依赖...")
layout.addWidget(self.label)
self.text = QTextEdit()
self.text.setReadOnly(True)
font = self.text.font()
font.setPointSizeF(font.pointSizeF() * 0.75) # 按比例缩小
self.text.setFont(font)
layout.addWidget(self.text)
self.setLayout(layout)
# 信号绑定槽
self.append_text.connect(self.text.append)
self.update_dep.connect(lambda name: self.label.setText(f"安装依赖中:{name}"))
def set_dep(self, name):
self.update_dep.emit(name)
def append(self, text):
self.append_text.emit(text)
# ------------------------
# 安装线程(实时输出pip日志)
# ------------------------
class InstallThread(QThread):
log_signal = pyqtSignal(str)
dep_signal = pyqtSignal(str)
finished_signal = pyqtSignal()
def __init__(self, packages, tools_libs, installed_deps):
super().__init__()
self.packages = packages
self.tools_libs = tools_libs
self._installed_deps = installed_deps
def run(self):
python_exe = sys.executable
for package in self.packages:
if package in self._installed_deps:
self.log_signal.emit(f"{package} 已安装过,跳过")
continue
self.dep_signal.emit(package)
self.log_signal.emit(f"开始安装依赖: {package}")
try:
# 使用 Popen 获取实时输出
process = subprocess.Popen(
[python_exe, "-m", "pip", "install", package, "--target", self.tools_libs],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True
)
# 实时读取输出
for line in iter(process.stdout.readline, ''):
if line:
self.log_signal.emit(line.rstrip())
process.stdout.close()
process.wait()
if process.returncode == 0:
self._installed_deps.add(package)
self.log_signal.emit(f"依赖安装成功: {package}")
else:
self.log_signal.emit(f"安装失败: {package}")
except Exception as e:
self.log_signal.emit(f"安装异常: {package} -> {e}")
self.finished_signal.emit()
# 自动依赖安装相关
PIP_MIRRORS = [
"https://pypi.tuna.tsinghua.edu.cn/simple",
"https://pypi.org/simple",
"https://mirrors.aliyun.com/pypi/simple",
"https://pypi.mirrors.ustc.edu.cn/simple",
]
class LoadingDialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("加载中...")
self.setModal(True)
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
layout = QtWidgets.QVBoxLayout(self)
self.label = QtWidgets.QLabel("正在加载...")
layout.addWidget(self.label)
self.resize(300, 100)
def update_text(self, text):
self.label.setText(text)
QtWidgets.QApplication.processEvents() # 刷新 UI
class CollapsibleSideBar(QWidget):
def __init__(self, main):
super().__init__()
self.main = main
self.expanded_width = 192
self.collapsed_width = 36
self.active_button = None
self.expanded = False
self.font_family = self.load_fontawesome()
self.resizing = False
self.initial_expanded = None
self.trigger_width = None
self.plugin_buttons = {} # plugin_name -> sidebar button
# 初始化UI
self.init_ui()
self.init_side_bar_state()
self.init_toolbar()
self.update_toolbar_state()
# 定时器用于检测拖动结束
self.resize_timer = QTimer(self)
self.resize_timer.setInterval(500) # 500ms 不再 resize 就认为拖动结束
self.resize_timer.setSingleShot(True)
self.resize_timer.timeout.connect(self.on_resize_finished)
def init_ui(self):
self.setWindowTitle("Win11 Task Manager Mockup")
self.resize(800, 500)
self.main_layout = QHBoxLayout(self)
self.main_layout.setContentsMargins(0, 0, 0, 0)
self.main_layout.setSpacing(0) # 添加这一行,设置主布局的间距为0
# 左侧列
self.side_bar = QWidget()
self.side_bar.setMaximumWidth(self.expanded_width)
self.side_bar.setObjectName("side_bar")
self.side_bar.setStyleSheet("""
QWidget#side_bar{
background-color: #e3e3e3;
}
""")
self.side_layout = QVBoxLayout(self.side_bar)
self.side_layout.setContentsMargins(0, 0, 0, 0)
self.side_layout.setSpacing(0)
# 收起/展开按钮
self.toggle_btn = QPushButton("≡")
self.toggle_btn.setFixedSize(30, 30)
self.toggle_btn.setFont(QFont("Arial", 11))
self.toggle_btn.setObjectName("toggle_btn")
self.toggle_btn.setToolTip("收起")
self.toggle_btn.setStyleSheet("""
QPushButton#toggle_btn {
text-align: center; /* 改为居中 */
padding-left: 0px; /* 移除左边距,或设为0 */
padding-bottom: 0px;
border: 1px solid #cccccc; /* 1px 描边 */
margin-top: 6px; /* 6px 外边距 */
margin-left: 6px; /* 6px 外边距 */
border-radius: 6px; /* 圆角 */
background-color: transparent;
}
QPushButton#toggle_btn:hover {
background-color: #cccccc;
}
""")
self.side_layout.addWidget(self.toggle_btn, alignment=Qt.AlignTop | Qt.AlignLeft)
self.toggle_btn.clicked.connect(self.toggle_side_bar)
# 重载按钮
self.reload_btn = QPushButton("↻")
self.reload_btn.setFixedSize(30, 30)
self.reload_btn.setFont(QFont("Arial", 11))
self.reload_btn.setToolTip("重载")
self.reload_btn.setObjectName("reload_btn")
self.reload_btn.setStyleSheet("""
QPushButton#reload_btn {
text-align: center; /* 改为居中 */
padding-left: 0px; /* 移除左边距,或设为0 */
padding-bottom: 0px;
border: 1px solid #cccccc; /* 1px 描边 */
margin-top: 6px; /* 6px 外边距 */
margin-left: 6px; /* 6px 外边距 */
border-radius: 6px; /* 圆角 */
background-color: transparent;
}
QPushButton#reload_btn:hover {
background-color: #cccccc;
}
""")
self.side_layout.addWidget(self.reload_btn, alignment=Qt.AlignTop | Qt.AlignLeft)
self.reload_btn.clicked.connect(self.main.on_reload)
# 滚动画布
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.scroll_area.setObjectName("side_scroll")
self.scroll_area.setStyleSheet("""
QScrollArea#side_scroll {
border: none; /* 去掉滚动区域的描边 */
background-color: #e3e3e3; /* 设置滚动区域背景色与左侧栏一致 */
}
QScrollBar:vertical {
width:6px; /* 整体宽度保持6px,这样悬停时才有空间变宽 */
background: #e3e3e3; /* 滚动条轨道背景色设为 e3e3e3 */
margin:0;
}
QScrollBar::handle:vertical {
background: gray;
min-height: 20px;
width:3px; /* 手柄默认宽度为3px */
border-radius:1.5px;
margin-left:1.5px; /* 通过左边距让手柄居中 */
}
QScrollBar::handle:vertical:hover {
background: #666666; /* 悬停时颜色加深 */
width:6px; /* 悬停时手柄宽度变为6px */
margin-left:0px; /* 悬停时取消左边距 */
border-radius:3px;
}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
height:0px;
}
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
background: #e3e3e3; /* 手柄上下区域的背景色设为 e3e3e3 */
}
""")
self.scroll_content = QWidget()
self.scroll_content.setObjectName("scroll_content")
self.scroll_content.setStyleSheet("""
QWidget#scroll_content {
background-color: transparent; /* 设置滚动区域背景色与左侧栏一致 */
}
""")
self.scroll_layout = QVBoxLayout(self.scroll_content)
self.scroll_layout.setContentsMargins(0, 0, 0, 0)
self.scroll_layout.setSpacing(0)
self.scroll_layout.setAlignment(Qt.AlignTop)
self.scroll_area.setWidget(self.scroll_content)
self.side_layout.addWidget(self.scroll_area)
#self.side_layout.addStretch()
# 初始化蓝色竖条,父控件改为 scroll_content
self.indicator = QLabel(self.scroll_content)
self.indicator.setFixedSize(3, 16) # 宽3px,高16px
self.indicator.setStyleSheet("""
background-color: #0078d7;
border-radius: 1px;
border: none;
""")
self.indicator.hide() # 初始隐藏
# 初始化完滚动区域之后
self.scroll_area.verticalScrollBar().valueChanged.connect(self.update_button_margins)
self.scroll_area.verticalScrollBar().rangeChanged.connect(self.update_button_margins)
# 右侧区域 - 修改部分
# 创建外部容器,背景色为#e3e3e3,内外边距为0
self.right_container = QWidget()
self.right_container.setObjectName("right_container")
#self.right_container.setStyleSheet("background-color: #e3e3e3;")
self.right_container.setStyleSheet("""
QWidget#right_container {
background-color: #e3e3e3;
}
""")
self.right_container.setContentsMargins(0, 0, 0, 0)
# 容器布局,边距为0
container_layout = QHBoxLayout(self.right_container)
container_layout.setContentsMargins(0, 0, 0, 0)
container_layout.setSpacing(0)
# 内部右侧区域,设置左上角8px圆角
self.right_area = QWidget()
self.right_area.setObjectName("right_area")
self.right_area.setStyleSheet("""
QWidget#right_area {
background-color: #f0f0f0;
border-top-left-radius: 6px;
border-top: 1px solid #cccccc; /* 上方1px描边 */
border-left: 1px solid #cccccc; /* 左侧1px描边 */
}
""")
# 内部布局
self.right_layout = QVBoxLayout(self.right_area)
self.right_layout.setContentsMargins(1, 1, 1, 1)
self.right_layout.setSpacing(0)
#self.right_layout.addWidget(QLabel("右侧内容区域,可放控件"))
#self.create_right_area_controls(self.right_layout)
# 将内部区域添加到容器布局中
container_layout.addWidget(self.right_area)
# 将容器添加到主布局
self.main_layout.addWidget(self.side_bar)
self.main_layout.addWidget(self.right_container)
"""# 1️⃣ 创建 splitter 替代 main_layout
self.splitter = QSplitter(Qt.Horizontal)
self.splitter.setHandleWidth(0) # 去掉中间 handle
self.splitter.addWidget(self.side_bar)
self.splitter.addWidget(self.right_container)
self.splitter.setStretchFactor(0, 0) # 左侧不拉伸
self.splitter.setStretchFactor(1, 1) # 右侧自适应
self.splitter.splitterMoved.connect(self.on_splitter_moved)
# 2️⃣ 将 splitter 添加到主窗口
self.main_layout.addWidget(self.splitter)"""
"""# 添加测试按钮
self.button_list = []
for i in range(10):
btn = self.create_button(f"测试按钮{i + 1}")
self.scroll_layout.addWidget(btn)
self.button_list.append(btn)
if self.button_list:
self.activate_button(self.button_list[0]) # 默认激活第一个按钮"""
"""self.splitter.splitterMoved.connect(self.on_splitter_moved)"""
# 更新按钮右边距
def update_button_margins(self):
# 延迟一帧执行
QTimer.singleShot(0, self._do_update_button_margins)
def _do_update_button_margins(self):
# 判断滚动条是否需要滚动(稳健方式)
scrollbar_needed = self.scroll_area.verticalScrollBar().maximum() > 0
right_margin = 0 if scrollbar_needed else 6
for btn in self.plugin_buttons.values():
if btn == self.active_button:
# 激活按钮保持背景色,仅更新右边距
btn.setStyleSheet(f"""
QPushButton {{
border: none;
border-radius: 6px;
background-color: #cccccc;
margin: 6px {right_margin}px 0px 6px;
padding: 0px;
}}
""")
else:
# 普通按钮
btn.setStyleSheet(f"""
QPushButton {{
border: none;
border-radius: 6px;
background-color: transparent;
margin: 6px {right_margin}px 0px 6px;
padding: 0px;
}}
QPushButton:hover {{
background-color: #cccccc;
}}
""")
def init_side_bar_state(self):
"""根据 self.expanded 初始化侧栏状态(无动画)"""
if self.expanded:
# 当前是展开逻辑(但你这里其实是“隐藏文本”的状态)
self.side_bar.setMaximumWidth(self.expanded_width)
self.side_bar.setMinimumWidth(self.expanded_width)
self.toggle_btn.setToolTip("收起")
else:
# 折叠状态
self.side_bar.setMaximumWidth(self.collapsed_width)
self.side_bar.setMinimumWidth(self.collapsed_width)
self.toggle_btn.setToolTip("展开")
# 同步所有按钮文本显示状态
for btn in self.plugin_buttons.values():
btn.text_label.setVisible(not self.expanded)
def init_toolbar(self):
"""初始化工具栏区域"""
# ===== 工具栏容器(始终在scroll_area下面)=====
self.toolbar_container = QWidget()
self.toolbar_container.setContentsMargins(0, 0, 0, 0)
self.toolbar_layout = QHBoxLayout(self.toolbar_container)
self.toolbar_layout.setContentsMargins(0, 0, 0, 0)
self.toolbar_layout.setSpacing(0)
# ===== 工具集按钮(侧栏收起时显示)=====
self.toolset_btn = QPushButton("🔧")
self.toolset_btn.setFixedSize(30, 30)
self.toolset_btn.setToolTip("工具栏")
# self.toolset_btn.setPointSizeF(6)
self.toolset_btn.setFont(QFont("", 11))
self.toolset_btn.setObjectName("toolset_btn")
# 使用和 toggle_btn 一样的样式,并增加 1px 描边
self.toolset_btn.setStyleSheet("""
QPushButton#toolset_btn {
text-align: center;
padding-top: 3px;
padding-bottom: 3px;
border: 1px solid #cccccc;
margin-bottom: 6px;
margin-left: 6px;
border-radius: 6px;
background-color: transparent;
}
QPushButton#toolset_btn:hover {
background-color: #cccccc;
}
""")
self.toolset_btn.clicked.connect(self.toggle_toolset_popup)
self.toolbar_layout.addWidget(self.toolset_btn, alignment=Qt.AlignLeft)
# ===== 工具集区域(真正的工具容器)=====
self.toolset_area = QWidget(self.right_container)
self.toolset_area.setFixedHeight(30)
self.toolset_area.hide()
# 创建水平滚动区域
self.toolset_scroll = QScrollArea(self.toolset_area)
self.toolset_scroll.setWidgetResizable(True)
self.toolset_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.toolset_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.toolset_scroll.setStyleSheet("""
QScrollArea {
border: none;
background: transparent;
padding-left: 6px;
}
QScrollArea > QWidget > QWidget {
background: transparent;
}
QScrollBar:horizontal {
height: 0px;
}
""")
# 安装事件过滤器,将鼠标竖向滚动转换为横向滚动
self.toolset_scroll.viewport().installEventFilter(self)
self.toolset_scroll.installEventFilter(self)
# 创建滚动内容容器
self.toolset_content = QWidget()
self.toolset_content.setFixedHeight(30)
self.toolset_layout = QHBoxLayout(self.toolset_content)
self.toolset_layout.setContentsMargins(0, 0, 0, 0)
self.toolset_layout.setSpacing(0)
self.toolset_layout.setAlignment(Qt.AlignLeft)
"""buttons = [
("\uf56f", "导入", lambda: None),
("\uf1f8", "删除", lambda: None),
("\uf51a", "清空", lambda: None),
("\uf0c5", "复制", lambda: None),
("\uf0c4", "剪切", lambda: None),
("\uf0ea", "粘贴", lambda: None),
]
self.tool_button(buttons)"""
self.toolset_scroll.setWidget(self.toolset_content)
# 删除这里重复设置的样式表
# self.toolset_scroll.setObjectName("toolset_scroll")
# self.toolset_scroll.setStyleSheet("""
# QWidget#toolset_scroll {
# background-color: transparent; /* 设置滚动区域背景色与左侧栏一致 */
# }
# """)
# 设置toolset_area的布局
toolset_area_layout = QHBoxLayout(self.toolset_area)
toolset_area_layout.setContentsMargins(0, 0, 0, 0)
toolset_area_layout.setSpacing(0)
toolset_area_layout.addWidget(self.toolset_scroll)
# 默认尺寸
self.toolset_area.setMinimumWidth(30)
self.toolset_area.setMaximumWidth(186)
# 插入到 scroll_area 下方
self.side_layout.addWidget(self.toolbar_container, alignment=Qt.AlignBottom)
def tool_button(self, buttons):
button_n = 0
for icon_unicode, name, action in buttons:
btn = QPushButton(icon_unicode)
btn.setToolTip(name)
btn.setFixedSize(30, 30) # 可根据需求调整大小
btn.setFont(QFont(self.font_family, 11)) # 调整大小
btn.setObjectName(f"tool_btn{button_n}")
btn.setStyleSheet(f"""
QPushButton#tool_btn{button_n} {{
text-align: center;
padding-left: 0px;
padding-bottom: 0px;
border: 0px solid #9a9a9a;
margin-bottom: 6px;
margin-left: 0px;
border-radius: 6px;
background-color: transparent;
}}
QPushButton#tool_btn{button_n}:hover {{
background-color: #cccccc;
}}
""")
btn.clicked.connect(action)
self.toolset_layout.addWidget(btn)
button_n += 1
# 添加事件过滤器方法
def eventFilter(self, obj, event):
"""事件过滤器,处理鼠标滚轮事件转换为横向滚动"""
if obj in (self.toolset_scroll, self.toolset_scroll.viewport()):
if event.type() == event.Type.Wheel:
# 获取滚轮事件的垂直滚动角度
delta = event.angleDelta().y()
# 如果有垂直滚动,转换为水平滚动
if delta != 0:
# 获取当前水平滚动条位置
h_scrollbar = self.toolset_scroll.horizontalScrollBar()
current_pos = h_scrollbar.value()
# 计算新的位置(向上滚动向左,向下滚动向右)
step = 40 # 每次滚动的步长,可以根据需要调整
if delta > 0:
new_pos = current_pos - step
else:
new_pos = current_pos + step
# 设置新的水平滚动条位置
h_scrollbar.setValue(new_pos)
# 事件已处理
return True
# 其他事件交给父类处理
return super().eventFilter(obj, event)
# 假设 self 是你的主窗口
def toggle_toolset_popup(self):
"""点击工具按钮弹出/关闭工具集"""
if self.toolset_area.isVisible():
self.toolset_area.hide()
return
# 弹出窗口设置
self.toolset_area.setParent(self)
self.toolset_area.setWindowFlags(Qt.FramelessWindowHint) # 无边框
self.toolset_area.setAttribute(Qt.WA_ShowWithoutActivating)
self.toolset_area.setObjectName("toolset_area")
self.toolset_area.setStyleSheet("""
QWidget#toolset_area {
border: 1px solid #cccccc;
background-color: #e3e3e3;
border-radius: 6px;
margin-bottom: 6px;
margin-left: 6px;
}
QScrollArea {
border: none;
background: transparent;
}
QScrollArea > QWidget > QWidget {
background: transparent;
}
QScrollBar:horizontal {
height: 0px;
}
""")
# ===== 计算按钮总宽度 =====
buttons = self.toolset_content.findChildren(QPushButton)
total_width = sum(btn.width() for btn in buttons) + 8 # +边距
min_width = 30
max_width = 186
popup_width = max(min_width, min(total_width, max_width))
self.toolset_area.setFixedWidth(popup_width) # 设置弹出窗口宽度
# 设置位置
global_pos = self.toolset_btn.mapToGlobal(self.toolset_btn.rect().topRight())
local_pos = self.mapFromGlobal(global_pos)
local_pos.setX(local_pos.x() + 8)
self.toolset_area.move(local_pos)
self.toolset_area.show()
# 刷新按钮状态
self.toolset_btn.setDown(False)
self.toolset_btn.repaint()
def update_toolbar_state(self):
"""更新工具栏状态(展开/收起)"""
if self.expanded:
# 收起按钮隐藏,工具集放入 toolbar_container 布局
self.toolset_btn.hide()
# 移除浮动属性
self.toolset_area.setParent(self.toolbar_container)
self.toolset_area.setWindowFlags(Qt.Widget) # 普通控件
# 清空toolset_area样式,让它透明
self.toolset_area.setStyleSheet("")
# 设置滚动区域在展开状态下也为透明
self.toolset_scroll.setStyleSheet("""
QScrollArea {
border: none;
background: transparent;
padding-left: 6px;
}
QScrollArea > QWidget > QWidget {
background: transparent;
}
QScrollBar:horizontal {
height: 0px;
}
""")
self.toolbar_layout.addWidget(self.toolset_area)
# 使用固定宽度展开
self.toolset_area.setMinimumWidth(self.expanded_width)
self.toolset_area.setMaximumWidth(self.expanded_width)
self.toolset_area.show()
else:
# 展开按钮显示,工具集变为浮动
self.toolset_btn.show()
self.toolset_area.setParent(self.right_container)
self.toolset_area.setWindowFlags(Qt.Popup)
self.toolset_area.setStyleSheet("""
QWidget#toolset_area {
border: 1px solid #cccccc;
background-color: #e3e3e3;
border-radius: 6px;
}
QScrollArea {
border: none;
background: transparent;
}
QScrollArea > QWidget > QWidget {
background: transparent;
}
QScrollBar:horizontal {
height: 0px;
}
""")
self.toolset_area.setMinimumWidth(30)
self.toolset_area.setMaximumWidth(400)
self.toolset_area.hide()
def update_toolset_position(self):
"""更新弹出工具栏的位置"""
if self.toolset_area.isVisible():
global_pos = self.toolset_btn.mapToGlobal(self.toolset_btn.rect().topRight())
local_pos = self.mapFromGlobal(global_pos)
# 增加间距
local_pos.setX(local_pos.x() + 8)
self.toolset_area.move(local_pos)
# 主窗口移动事件时,让浮动工具集跟随
def moveEvent(self, event):
super().moveEvent(event)
self.update_toolset_position()
def resizeEvent(self, event):
super().resizeEvent(event)
self.update_toolset_position()
self.on_resize_event()
def on_resize_event(self):
"""处理侧栏自动展开/收起逻辑"""
# 每次 resize 都重启定时器
self.resize_timer.start()
if not self.resizing:
# 第一次 resize 时,认为开始调整
self.resizing = True
self.initial_expanded = self.expanded # 记录调整前状态
if not self.initial_expanded:
return # 调整前侧栏收起,不处理
window_width = self.width()
side_width = self.side_bar.width()
ratio = side_width / window_width
if self.trigger_width is None:
if self.expanded and ratio >= 0.3:
self.toggle_side_bar() # 收起
self.trigger_width = window_width
else:
if window_width > self.trigger_width:
if not self.expanded:
self.toggle_side_bar() # 展开
elif window_width < self.trigger_width:
if self.expanded:
self.toggle_side_bar() # 收起
def on_resize_finished(self):
"""拖动结束,清空状态"""
self.resizing = False
self.trigger_width = None
self.initial_expanded = None
def create_button(self, text, icon=None):
btn = QPushButton()
btn.setCheckable(False)
btn.setFixedHeight(30) # 固定高度
# 按钮样式
btn.setStyleSheet("""
QPushButton {
border: none;
border-radius: 6px;
background-color: transparent;
margin: 6px 6px 0px 6px; /* 上 右 下 左 */
padding: 0px;
}
QPushButton:hover {
background-color: #cccccc;
}
""")
layout = QHBoxLayout(btn)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
# ===== 图标 =====
icon_widget = QLabel()
icon_widget.setAlignment(Qt.AlignCenter)
icon_widget.setFixedSize(36, 36)
icon_widget.setStyleSheet("""
QLabel {
background-color: transparent;
border: 1px solid #cccccc; /* 1px 描边 */
border-radius: 6px;
margin: 6px 6px 6px 6px; /* 上 右 下 左 */
padding: 0px;
}
""")
icon_widget.setAttribute(Qt.WA_TransparentForMouseEvents)
if icon:
# 文件图标
if "file" in icon:
file_icon = QIcon(icon["file"])
icon_widget.setPixmap(file_icon.pixmap(QSize(24, 24)))
# 文本图标
elif "text" in icon:
chars = icon["text"]
num_chars = len(chars)
if num_chars == 1:
icon_widget.setFont(QFont("", 11))
icon_widget.setText(chars)
elif num_chars == 2:
icon_widget.setFont(QFont("", 9))
icon_widget.setText(chars)
else:
# 三字符及以上使用两行两列的排列(类似原来的逻辑)
display_chars = chars[:4].ljust(4)
icon_widget.setFont(QFont("", 6))
icon_widget.setText(f"{display_chars[:2]}\n{display_chars[2:]}")
elif "text_ico" in icon:
chars = icon["text_ico"]
num_chars = len(chars)
if num_chars == 1:
icon_widget.setFont(QFont(self.font_family, 11))
icon_widget.setText(chars)
elif num_chars == 2:
icon_widget.setFont(QFont(self.font_family, 9))
icon_widget.setText(chars)
else:
# 三字符及以上使用两行两列的排列(类似原来的逻辑)
display_chars = chars[:4].ljust(4)
icon_widget.setFont(QFont(self.font_family, 6))
icon_widget.setText(f"{display_chars[:2]}\n{display_chars[2:]}")
else:
# 默认文本生成图标
chars = text[:4].ljust(4)
icon_widget.setFont(QFont("Arial", 6))
icon_widget.setText(f"{chars[:2]}\n{chars[2:]}")
# ===== 文本 =====
text_label = QLabel(text)
text_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
text_label.setFont(QFont("Arial", 9))
text_label.setStyleSheet("""
background: transparent;
padding: 0px;
""")
text_label.setFixedHeight(36)
text_label.setMinimumWidth(0)
text_label.setAttribute(Qt.WA_TransparentForMouseEvents)
layout.addWidget(icon_widget)
layout.addWidget(text_label)
layout.addStretch() # 让文本扩展