-
Notifications
You must be signed in to change notification settings - Fork 314
Expand file tree
/
Copy pathGUIkhQuant.py
More file actions
5476 lines (4647 loc) · 226 KB
/
GUIkhQuant.py
File metadata and controls
5476 lines (4647 loc) · 226 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 sys
import os
import logging
import psutil
import time
import traceback
import json
import subprocess
import shutil
from datetime import datetime
from PyQt5.QtCore import (
Qt,
QSettings,
QTimer,
QThread,
pyqtSignal,
QMetaType,
pyqtSlot,
QDateTime,
QDate,
Q_ARG,
QTime,
QEvent,
QUrl,
QMetaObject,
)
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout,
QTableWidget, QTableWidgetItem, QMenu, QAction, QFileDialog, QMessageBox, QSplitter,
QTabWidget, QTextEdit, QComboBox, QGroupBox, QLineEdit, QDateEdit, QCheckBox, QProgressDialog,
QSizePolicy, QScrollArea, QTreeWidget, QTreeWidgetItem, QStackedWidget, QDialog, QListWidget,
QListWidgetItem, QSlider, QFrame, QToolBar, QButtonGroup, QRadioButton, QSpinBox, QDoubleSpinBox,
QCalendarWidget, QTimeEdit, QFormLayout, QSpacerItem, QGridLayout, QStatusBar, QInputDialog,
QHeaderView, QStyleFactory, QGraphicsDropShadowEffect, QProgressBar, QSplashScreen, QToolButton,
QDesktopWidget)
from PyQt5.QtGui import QIcon, QCursor, QFont, QColor, QPainter, QPen, QBrush, QPixmap, QTextCursor, QPalette, QDoubleValidator, QIntValidator, QDesktopServices
# 导入GUI模块中的StockDataProcessorGUI类
try:
from GUI import StockDataProcessorGUI, setup_logging
except ImportError:
logging.error("无法导入GUI模块中的StockDataProcessorGUI类")
StockDataProcessorGUI = None
setup_logging = None
# 导入数据管理模块
try:
from GUIDataViewer import GUIDataViewer # 数据本地数据管理模块
except ImportError:
logging.error("无法导入数据查看器模块")
GUIDataViewer = None
try:
from GUIScheduler import GUIScheduler # 数据定时补充模块
except ImportError:
logging.error("无法导入数据定时补充模块")
GUIScheduler = None
# 导入其他必要的模块
try:
from khFrame import KhQuantFramework, MyTraderCallback
from khQTTools import get_stock_names
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
except ImportError as e:
logging.error(f"导入必要模块失败: {str(e)}")
from SettingsDialog import SettingsDialog
from PyQt5.QtCore import QSettings
from update_manager import UpdateManager # 导入UpdateManager类
from version import get_version_info # 导入版本信息
# 配置日志系统
def get_logs_dir():
"""获取日志目录的正确路径"""
base_dir = os.path.dirname(__file__)
logs_dir = os.path.join(base_dir, 'logs')
try:
os.makedirs(logs_dir, exist_ok=True)
print(f"使用日志目录: {logs_dir}")
return logs_dir
except (OSError, PermissionError) as e:
print(f"无法使用日志目录 {logs_dir}: {e}")
# 备用目录
import tempfile
logs_dir = os.path.join(tempfile.gettempdir(), 'KhQuant_logs')
os.makedirs(logs_dir, exist_ok=True)
print(f"使用临时日志目录: {logs_dir}")
return logs_dir
LOGS_DIR = get_logs_dir()
# 配置日志,添加异常处理
try:
logging.basicConfig(
filename=os.path.join(LOGS_DIR, 'app.log'),
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
filemode='w',
encoding='utf-8'
)
print(f"日志文件配置成功: {os.path.join(LOGS_DIR, 'app.log')}")
except Exception as e:
# 如果文件日志配置失败,只使用控制台日志
print(f"配置文件日志失败: {e}")
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# 添加控制台日志处理器(仅在标准错误可用时)
_stderr_stream = getattr(sys, 'stderr', None)
if _stderr_stream and hasattr(_stderr_stream, 'write'):
console_handler = logging.StreamHandler(_stderr_stream)
console_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
logging.getLogger('').addHandler(console_handler)
# 定义StockAccount类
class StockAccount:
"""账户类"""
def __init__(self, account_id, account_type="STOCK"):
self.account_id = account_id
self.account_type = account_type
self.total_asset = 0.0
self.cash = 0.0
self.market_value = 0.0
self.positions = []
class StrategyThread(QThread):
"""策略运行线程"""
# 定义信号
error_signal = pyqtSignal(str, Exception) # 错误信号
status_signal = pyqtSignal(str) # 状态信号
finished_signal = pyqtSignal() # 完成信号
def __init__(self, config_path, strategy_file, trader_callback):
super().__init__()
self.config_path = config_path
self.strategy_file = strategy_file
self.trader_callback = trader_callback
self.framework = None
self._is_running = True
def run(self):
"""线程运行函数"""
try:
# 创建框架实例
self.framework = KhQuantFramework(
self.config_path,
self.strategy_file,
trader_callback=self.trader_callback
)
# 发送状态信号
self.status_signal.emit("框架实例创建成功")
# 运行策略
self.framework.run()
except Exception as e:
# 发送错误信号
self.error_signal.emit("策略运行异常", e)
import traceback
self.trader_callback.gui.log_message(f"错误详情:\n{traceback.format_exc()}", "ERROR")
finally:
# 发送完成信号(在设置_is_running=False之前)
self.finished_signal.emit()
# 现在设置运行状态为False
self._is_running = False
def stop(self):
"""停止策略"""
self._is_running = False
if self.framework:
self.framework.stop()
@property
def is_running(self):
return self._is_running
class GUILogHandler(logging.Handler):
"""自定义日志处理器,将日志信息显示在GUI的运行日志表格中"""
def __init__(self, gui):
super().__init__()
self.gui = gui
def emit(self, record):
try:
msg = self.format(record)
# 使用Qt的信号槽机制来更新GUI
self.gui.log_signal.emit(msg, record.levelname)
except Exception:
self.handleError(record)
class KhQuantGUI(QMainWindow):
# 添加Qt信号
log_signal = pyqtSignal(str, str)
update_status_signal = pyqtSignal(str, str)
show_backtest_result_signal = pyqtSignal(str) # 添加新信号
progress_signal = pyqtSignal(int) # 添加进度条信号
def __init__(self):
super().__init__()
# 记录程序启动时间
self.start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 初始化设置
self.settings = QSettings('KHQuant', 'StockAnalyzer')
# 初始化延迟日志显示相关属性(需要在早期初始化,避免AttributeError)
self.delay_log_display = self.settings.value('delay_log_display', True, type=bool)
self.delayed_logs = []
self.strategy_is_running = False
self.max_log_lines = self.settings.value('max_log_lines', 1000, type=int) # 最大日志显示行数
# 检测屏幕分辨率并设置字体缩放
self.font_scale = self.detect_screen_resolution()
# 设置应用样式表
self.setStyleSheet(self.get_scaled_stylesheet())
# 初始化属性
self.config = {}
self.trader = None
self.trader_callback = None
self.stock_data_manager = None
# 日志过滤器设置
self.filter_log_levels = {"INFO": True, "DEBUG": True, "WARNING": True, "ERROR": True}
self.current_config_file = None # 当前加载的配置文件路径
# 设置窗口属性
self.setWindowTitle("看海量化回测系统")
# 设置窗口图标
self.setWindowIcon(QIcon(self.get_icon_path("stock_icon.ico")))
# 边框样式已在init_ui中设置,这里不再重复设置
# 初始化更新管理器
self.initialize_update_manager()
# 初始化UI组件
self.init_ui()
# 初始化配置
self.init_config()
# 记录日志
logging.info("GUI初始化完成")
# 初始化属性
self.strategy_thread = None
self.log_handler = GUILogHandler(self)
self.log_handler.setLevel(logging.INFO)
# 日志存储
self.log_entries = []
# 更新实盘数据获取模块状态
self.update_realtime_data_group_status()
# 连接信号到槽(使用QueuedConnection确保跨线程调用不阻塞)
self.log_signal.connect(self._log_message, Qt.QueuedConnection)
self.update_status_signal.connect(self._update_status_table, Qt.QueuedConnection)
self.show_backtest_result_signal.connect(self.show_backtest_result, Qt.QueuedConnection)
self.progress_signal.connect(self.update_progress_bar, Qt.QueuedConnection)
# 设置定时器定期刷新日志缓冲区
self.log_flush_timer = QTimer()
self.log_flush_timer.timeout.connect(self.flush_logs)
self.log_flush_timer.start(5000) # 每5秒刷新一次日志
# 初始化代码编辑器模块(已废弃,现在使用EmbeddedVSCodeManager)
self.editor_module = None
# if get_editor_module is not None:
# try:
# self.editor_module = get_editor_module(self)
# logging.info("代码编辑器模块初始化成功")
# 调试模式相关属性(开源版本不支持内置调试)
self.debug_mode_enabled = False
self.debug_manager = None
# 记录启动信息到日志
logging.info(f"软件启动时间: {self.start_time}")
logging.info(f"当前版本: {get_version_info()['version']}")
logging.info(f"日志文件路径: {os.path.join(LOGS_DIR, 'app.log')}")
# 最后确保窗口在主屏幕居中显示(放在初始化的最末尾)
self.center_window()
self.show()
# 初始化数据管理窗口实例变量
self.csv_manager_window = None
self.data_viewer_window = None
self.scheduler_window = None
def get_icon_path(self, icon_name):
"""获取图标文件的正确路径"""
return os.path.join(os.path.dirname(__file__), 'icons', icon_name)
def get_data_path(self, filename):
"""获取数据文件的正确路径"""
return os.path.join(os.path.dirname(__file__), 'data', filename)
def detect_screen_resolution(self):
"""检测屏幕分辨率并返回字体缩放比例"""
from PyQt5.QtWidgets import QApplication
screen = QApplication.desktop().screenGeometry()
width = screen.width()
height = screen.height()
# 根据屏幕宽度确定字体缩放比例
if width >= 3840: # 4K及以上分辨率
return 1.8
elif width >= 2560: # 2K分辨率
return 1.4
elif width >= 1920: # 1080P分辨率
return 1.0
else: # 低分辨率
return 0.8
def get_scaled_stylesheet(self):
"""获取根据分辨率缩放的样式表"""
# 基础字体大小
base_sizes = {
'small': 12,
'normal': 14,
'large': 16,
'xl': 18,
'xxl': 24,
'xxxl': 30
}
# 计算缩放后的字体大小
scaled_sizes = {k: int(v * self.font_scale) for k, v in base_sizes.items()}
# 计算缩放后的复选框指示器大小
checkbox_indicator_size = max(20, int(20 * self.font_scale))
return f"""
/* 主窗口和基础样式 */
QMainWindow {{
background-color: #2b2b2b;
color: #e8e8e8;
border: 3px solid #c0c0c0;
font-size: {scaled_sizes['normal']}px;
}}
QWidget {{
background-color: #2b2b2b;
color: #e8e8e8;
font-size: {scaled_sizes['normal']}px;
}}
/* 分组框样式 */
QGroupBox {{
background-color: #333333;
border: 1px solid #404040;
border-radius: 6px;
margin-top: 1em;
padding-top: 1em;
color: #e8e8e8;
font-size: {scaled_sizes['normal']}px;
}}
QGroupBox::title {{
subcontrol-origin: margin;
left: 10px;
padding: 0 5px;
color: #e8e8e8;
font-weight: bold;
background-color: #333333;
font-size: {scaled_sizes['normal']}px;
}}
/* 标签样式 */
QLabel {{
color: #e8e8e8;
background-color: transparent;
font-size: {scaled_sizes['normal']}px;
}}
/* 链接样式 */
QLabel[linkEnabled="true"] {{
color: #a0a0a0;
font-size: {scaled_sizes['normal']}px;
}}
QLabel[linkEnabled="true"]:hover {{
color: #ffffff;
}}
/* 输入框样式 */
QLineEdit {{
background-color: #404040;
border: 1px solid #4d4d4d;
border-radius: 4px;
padding: 5px;
color: #e8e8e8;
selection-background-color: #666666;
font-size: {scaled_sizes['normal']}px;
}}
QLineEdit:focus {{
border: 1px solid #737373;
background-color: #454545;
}}
/* 按钮样式 */
QPushButton {{
background-color: #505050;
border: none;
border-radius: 4px;
padding: 8px 16px;
color: #e8e8e8;
min-width: 80px;
font-weight: bold;
font-size: {scaled_sizes['normal']}px;
}}
QPushButton:hover {{
background-color: #606060;
}}
QPushButton:pressed {{
background-color: #454545;
}}
QPushButton:disabled {{
background-color: #404040;
color: #808080;
}}
/* 下拉框样式 */
QComboBox {{
background-color: #404040;
border: 1px solid #4d4d4d;
border-radius: 4px;
padding: 5px;
color: #e8e8e8;
min-width: 100px;
font-size: {scaled_sizes['normal']}px;
}}
QComboBox:hover {{
border: 1px solid #666666;
}}
QComboBox::drop-down {{
border: none;
width: 20px;
background-color: transparent;
}}
QComboBox::down-arrow {{
image: none;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 8px solid #e8e8e8;
margin-right: 6px;
margin-top: 2px;
}}
QComboBox::down-arrow:hover {{
border-top: 8px solid #ffffff;
}}
QComboBox QAbstractItemView {{
background-color: #404040;
border: 1px solid #4d4d4d;
selection-background-color: #666666;
selection-color: #ffffff;
font-size: {scaled_sizes['normal']}px;
}}
/* 表格样式 */
QTableWidget {{
background-color: #333333;
alternate-background-color: #383838;
border: 1px solid #404040;
color: #e8e8e8;
gridline-color: #404040;
font-size: {scaled_sizes['normal']}px;
}}
QTableWidget::item {{
padding: 5px;
background-color: transparent;
}}
QTableWidget::item:selected {{
background-color: #505050;
color: #ffffff;
}}
QHeaderView::section {{
background-color: #404040;
color: #e8e8e8;
padding: 8px;
border: none;
border-right: 1px solid #4d4d4d;
border-bottom: 1px solid #4d4d4d;
font-weight: bold;
font-size: {scaled_sizes['normal']}px;
}}
QTableCornerButton::section {{
background-color: #404040;
border: none;
border-right: 1px solid #4d4d4d;
border-bottom: 1px solid #4d4d4d;
}}
QTableCornerButton::section:pressed {{
background-color: #505050;
}}
QHeaderView::section:vertical {{
background-color: #404040;
color: #e8e8e8;
padding: 5px;
border: none;
border-right: 1px solid #4d4d4d;
border-bottom: 1px solid #4d4d4d;
font-size: {scaled_sizes['normal']}px;
}}
QHeaderView::section:vertical:hover {{
background-color: #454545;
}}
QHeaderView::section:vertical:pressed {{
background-color: #505050;
}}
/* 滚动条样式 */
QScrollBar:vertical {{
background-color: #3a3a3a;
width: 15px;
border: none;
}}
QScrollBar::handle:vertical {{
background-color: #5a5a5a;
border-radius: 7px;
min-height: 20px;
}}
QScrollBar::handle:vertical:hover {{
background-color: #6a6a6a;
}}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{
border: none;
background: none;
}}
QScrollBar:horizontal {{
background-color: #3a3a3a;
height: 15px;
border: none;
}}
QScrollBar::handle:horizontal {{
background-color: #5a5a5a;
border-radius: 7px;
min-width: 20px;
}}
QScrollBar::handle:horizontal:hover {{
background-color: #6a6a6a;
}}
QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {{
border: none;
background: none;
}}
/* 复选框样式 */
QCheckBox {{
color: #e8e8e8;
spacing: 5px;
font-size: {scaled_sizes['normal']}px;
background-color: transparent;
}}
QCheckBox::indicator {{
width: {checkbox_indicator_size}px;
height: {checkbox_indicator_size}px;
border: 1px solid #666666;
border-radius: 3px;
background-color: #404040;
}}
QCheckBox::indicator:checked {{
background-color: #007acc;
border: 1px solid #007acc;
image: none;
}}
QCheckBox::indicator:hover {{
border: 1px solid #666666;
}}
/* 单选按钮样式 */
QRadioButton {{
color: #e8e8e8;
spacing: 5px;
font-size: {scaled_sizes['normal']}px;
}}
QRadioButton::indicator {{
width: 18px;
height: 18px;
border: 1px solid #4d4d4d;
border-radius: 9px;
background-color: #404040;
}}
QRadioButton::indicator:checked {{
background: qradialgradient(cx:0.5, cy:0.5, radius:0.4,
stop:0 white, stop:0.4 white, stop:0.5 #007acc, stop:1 #007acc);
border: 1px solid #007acc;
}}
QRadioButton::indicator:hover {{
border: 1px solid #666666;
}}
/* 旋转框样式 */
QSpinBox, QDoubleSpinBox {{
background-color: #404040;
border: 1px solid #4d4d4d;
border-radius: 4px;
padding: 5px;
color: #e8e8e8;
font-size: {scaled_sizes['normal']}px;
}}
QSpinBox:focus, QDoubleSpinBox:focus {{
border: 1px solid #737373;
background-color: #454545;
}}
QSpinBox::up-button, QDoubleSpinBox::up-button {{
subcontrol-origin: border;
subcontrol-position: top right;
width: 16px;
border-left: 1px solid #4d4d4d;
background-color: #505050;
}}
QSpinBox::down-button, QDoubleSpinBox::down-button {{
subcontrol-origin: border;
subcontrol-position: bottom right;
width: 16px;
border-left: 1px solid #4d4d4d;
background-color: #505050;
}}
QSpinBox::up-arrow, QDoubleSpinBox::up-arrow {{
image: none;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-bottom: 6px solid #e8e8e8;
margin-left: 4px;
}}
QSpinBox::down-arrow, QDoubleSpinBox::down-arrow {{
image: none;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 6px solid #e8e8e8;
margin-left: 4px;
}}
/* 日期时间编辑器样式 */
QDateEdit, QTimeEdit, QDateTimeEdit {{
background-color: #404040;
border: 1px solid #4d4d4d;
border-radius: 4px;
padding: 5px;
color: #e8e8e8;
font-size: {scaled_sizes['normal']}px;
}}
QDateEdit:focus, QTimeEdit:focus, QDateTimeEdit:focus {{
border: 1px solid #737373;
background-color: #454545;
}}
QDateEdit::drop-down, QTimeEdit::drop-down, QDateTimeEdit::drop-down {{
subcontrol-origin: padding;
subcontrol-position: top right;
width: 20px;
border-left: 1px solid #4d4d4d;
background-color: #505050;
}}
QDateEdit::down-arrow, QTimeEdit::down-arrow, QDateTimeEdit::down-arrow {{
image: none;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 8px solid #e8e8e8;
margin-right: 2px;
}}
/* 文本编辑器样式 */
QTextEdit, QPlainTextEdit {{
background-color: #2b2b2b;
border: 1px solid #404040;
border-radius: 4px;
color: #e8e8e8;
selection-background-color: #505050;
font-family: "Consolas", "Microsoft YaHei", monospace;
font-size: {scaled_sizes['large']}px;
}}
/* 进度条样式 */
QProgressBar {{
background-color: #404040;
border: 1px solid #4d4d4d;
border-radius: 5px;
text-align: center;
font-size: {scaled_sizes['normal']}px;
}}
QProgressBar::chunk {{
background-color: #007acc;
border-radius: 4px;
}}
/* 状态栏样式 */
QStatusBar {{
background-color: #3a3a3a;
color: #e8e8e8;
border-top: 1px solid #4d4d4d;
font-size: {scaled_sizes['normal']}px;
}}
/* 菜单栏样式 */
QMenuBar {{
background-color: #333333;
color: #e8e8e8;
border-bottom: 1px solid #404040;
font-size: {scaled_sizes['normal']}px;
}}
QMenuBar::item {{
background-color: transparent;
padding: 4px 8px;
}}
QMenuBar::item:selected {{
background-color: #505050;
}}
/* 菜单样式 */
QMenu {{
background-color: #333333;
border: 1px solid #404040;
color: #e8e8e8;
font-size: {scaled_sizes['normal']}px;
}}
QMenu::item {{
padding: 6px 20px;
background-color: transparent;
}}
QMenu::item:selected {{
background-color: #505050;
}}
QMenu::separator {{
height: 1px;
background-color: #404040;
margin: 2px 0px;
}}
/* 工具栏样式 */
QToolBar {{
background-color: #333333;
border: none;
spacing: 2px;
font-size: {scaled_sizes['normal']}px;
}}
QToolBar::separator {{
background-color: #404040;
width: 1px;
margin: 2px;
}}
/* 工具提示样式 */
QToolTip {{
background-color: #555555;
color: #e8e8e8;
border: 1px solid #666666;
padding: 4px;
border-radius: 3px;
font-size: {scaled_sizes['small']}px;
}}
/* Tab样式 */
QTabWidget::pane {{
border: 1px solid #404040;
background-color: #333333;
}}
QTabBar::tab {{
background-color: #404040;
color: #e8e8e8;
padding: 8px 16px;
margin-right: 2px;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
font-size: {scaled_sizes['normal']}px;
}}
QTabBar::tab:selected {{
background-color: #333333;
border-bottom: 2px solid #007acc;
}}
QTabBar::tab:hover {{
background-color: #505050;
}}
/* 分割器样式 */
QSplitter::handle {{
background-color: #404040;
}}
QSplitter::handle:horizontal {{
width: 2px;
}}
QSplitter::handle:vertical {{
height: 2px;
}}
/* 自定义信号指示器样式 */
.signal-indicator {{
border-radius: 10px;
font-size: {scaled_sizes['small']}px;
font-weight: bold;
}}
/* 自定义logo文本样式 */
.logo-text {{
font-size: {scaled_sizes['normal']}px;
}}
/* 启动画面样式 */
.splash-screen {{
background-color: #2b2b2b;
border: 2px solid #404040;
font-size: {scaled_sizes['large']}px;
font-weight: bold;
}}
/* 进度文本样式 */
.progress-text {{
font-size: {scaled_sizes['normal']}px;
}}
"""
def log_message(self, message, level="INFO"):
"""发送日志信号"""
self.log_signal.emit(message, level)
def log_error(self, error_msg, error):
"""记录错误日志"""
message = f"{error_msg}: {str(error)}"
self.log_message(message, "ERROR")
import traceback
self.log_message(f"错误详情:\n{traceback.format_exc()}", "ERROR")
def flush_logs(self):
"""强制刷新日志缓冲区,确保日志及时写入文件"""
try:
for handler in logging.getLogger().handlers:
if hasattr(handler, 'flush'):
handler.flush()
except Exception as e:
# 避免在日志刷新时产生新的异常循环
print(f"刷新日志时出错: {e}")
def showEvent(self, event):
"""窗口显示事件"""
super().showEvent(event)
# 移除强制最大化,让窗口保持居中显示
def changeEvent(self, event):
"""窗口状态变化事件,处理窗口还原时居中显示"""
super().changeEvent(event)
if event.type() == QEvent.WindowStateChange:
if not self.isMaximized() and not self.isMinimized():
# 窗口处于正常状态(非最大化非最小化),进行居中显示
self.center_window()
def center_window(self):
"""将窗口居中显示在主屏幕"""
# 设置窗口大小为屏幕尺寸的80%
# 使用主屏幕而不是跟随鼠标位置
desktop = QDesktopWidget()
primary_screen = desktop.primaryScreen()
screen = desktop.availableGeometry(primary_screen)
width = int(screen.width() * 0.7)
height = int(screen.height() * 0.7)
self.resize(width, height)
# 计算居中位置(基于主屏幕)
qr = self.frameGeometry()
cp = screen.center()
qr.moveCenter(cp)
self.move(qr.topLeft())
# 边框样式已在init_ui中设置,这里不再重复设置
def init_ui(self):
# 设置窗口标题栏颜色(仅适用于Windows)
if sys.platform == 'win32':
try:
from ctypes import windll, c_int, byref, sizeof, create_string_buffer, create_unicode_buffer, Structure, POINTER
from ctypes.wintypes import DWORD, HWND, BOOL
# 定义必要的Windows API常量和结构
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
DWMWA_CAPTION_COLOR = 35 # 标题栏颜色
# 启用深色模式
windll.dwmapi.DwmSetWindowAttribute(
int(self.winId()),
DWMWA_USE_IMMERSIVE_DARK_MODE,
byref(c_int(2)), # 2 means true
sizeof(c_int)
)
# 设置标题栏颜色
caption_color = DWORD(0x2b2b2b) # 使用与主界面相同的颜色
windll.dwmapi.DwmSetWindowAttribute(
int(self.winId()),
DWMWA_CAPTION_COLOR,
byref(caption_color),
sizeof(caption_color)
)
except Exception as e:
logging.warning(f"设置标题栏深色模式失败: {str(e)}")
# 设置根据分辨率缩放的深色主题样式表
self.setStyleSheet(self.get_scaled_stylesheet())
# 创建自定义日志处理器(移到最前面)
self.log_handler = GUILogHandler(self)
self.log_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logging.getLogger('').addHandler(self.log_handler)
# 设置窗口标题
self.setWindowTitle("看海量化回测系统")
# 设置窗口图标
logo_path = self.get_icon_path("stock_icon.ico")
if os.path.exists(logo_path):
self.setWindowIcon(QIcon(logo_path))
else:
# 尝试png格式
logo_path_png = self.get_icon_path("stock_icon.png")
if os.path.exists(logo_path_png):
self.setWindowIcon(QIcon(logo_path_png))
else:
self.log_message(f"图标文件不存在: {logo_path}", "WARNING")
# 创建工具栏
self.create_toolbar()
# 创建主窗口部件和布局
main_widget = QWidget()
self.setCentralWidget(main_widget)
# 添加状态栏
self.status_bar = QStatusBar()
self.setStatusBar(self.status_bar)
# 添加状态标签(放在右侧)
self.status_label = QLabel("就绪")
self.status_label.setFixedWidth(100)
self.status_bar.addPermanentWidget(self.status_label)
# 进度条容器:叠放进度条与文本,保证文本浮在上方
class ProgressOverlay(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(6)
# 进度条(左侧)
self.bar = QProgressBar(self)
self.bar.setTextVisible(False)
self.bar.setRange(0, 100)
self.bar.setValue(0)
self.bar.setFormat("") # 禁止进度条自绘文字
self.bar.setFixedHeight(16)
self.bar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
layout.addWidget(self.bar, 1)
# 右侧文本
self.label = QLabel("回测进度: 0%", self)
self.label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
self.label.setStyleSheet("""
QLabel {
color: white;
font-weight: bold;
background: transparent;
padding-left: 2px;
}
""")
self.label.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
layout.addWidget(self.label, 0)
# 使用自定义覆盖控件
self.progress_container = ProgressOverlay()
self.progress_bar = self.progress_container.bar
self.progress_text = self.progress_container.label
# 添加到状态栏
self.status_bar.addWidget(self.progress_container, 1)
# 默认隐藏进度条
self.progress_container.hide()
# 设置状态栏样式
self.status_bar.setStyleSheet("""
QStatusBar {
background-color: #333333;
color: #e8e8e8;
padding: 2px;
border-top: 1px solid #404040;
}
QStatusBar::item {
border: none;
}
""")
# 确保状态栏可见