-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathui_main_qt.py
More file actions
2059 lines (1815 loc) · 86.6 KB
/
Copy pathui_main_qt.py
File metadata and controls
2059 lines (1815 loc) · 86.6 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
"""
VLM 机器人抓取 - PyQt5 图形界面控制台
运行方式: conda activate vlm_graspnet_RRT && python ui_main_qt.py
"""
import os, sys
# ── 必须在所有其他 import 之前:修正 LD_LIBRARY_PATH 后重启自身 ──────────────
# 原因:conda base 的 /home/robot/anaconda3/lib/ 含 Qt 5.15.2,
# PyQt5 是 Qt 5.15.18,两者共存会触发 "Cannot mix incompatible Qt library"。
# LD_LIBRARY_PATH 修改只对子进程生效,所以用 os.execv 重启来继承新路径。
_REEXEC_FLAG = "_PYQT5_LD_FIXED"
if not os.environ.get(_REEXEC_FLAG):
try:
import PyQt5 as _p
_qt_lib = os.path.join(os.path.dirname(_p.__file__), "Qt5", "lib")
_qt_plug = os.path.join(os.path.dirname(_p.__file__), "Qt5", "plugins")
_old_ld = os.environ.get("LD_LIBRARY_PATH", "")
os.environ["LD_LIBRARY_PATH"] = _qt_lib + (":" + _old_ld if _old_ld else "")
os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = _qt_plug
os.environ[_REEXEC_FLAG] = "1"
os.execv(sys.executable, [sys.executable] + sys.argv)
except Exception as e:
print(f"[UI] LD_LIBRARY_PATH 设置失败,继续尝试: {e}")
import threading, queue, time, io, math
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(ROOT_DIR, 'graspnet-baseline', 'models'))
sys.path.append(os.path.join(ROOT_DIR, 'graspnet-baseline', 'dataset'))
sys.path.append(os.path.join(ROOT_DIR, 'graspnet-baseline', 'utils'))
sys.path.append(os.path.join(ROOT_DIR, 'manipulator_grasp'))
import cv2
import numpy as np
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QLineEdit, QTextEdit, QScrollArea,
QFrame, QRadioButton, QButtonGroup, QDialog, QDialogButtonBox,
QSizePolicy, QComboBox, QSplitter, QGraphicsDropShadowEffect, QListWidget, QSpinBox, QSlider
)
from PyQt5.QtCore import (
Qt, QTimer, QObject, pyqtSignal, QThread, QSize, QPointF,
QPropertyAnimation, QEasingCurve, QRect, QSequentialAnimationGroup
)
from PyQt5.QtGui import (
QFont, QPixmap, QImage, QColor, QPalette, QFontDatabase,
QPainter, QPolygonF, QPainterPath, QPen
)
# ── 颜色常量 ──────────────────────────────────────────────
BG_DARK = "#0a0a14"
BG_PANEL = "#0f111a"
BG_CARD = "#151822"
BG_INPUT = "#1a1e2e"
BORDER_CLR = "#1e2235"
CYAN = "#22d3ee"
CYAN_DIM = "#164e63"
INDIGO = "#818cf8"
INDIGO_DIM = "#312e81"
EMERALD = "#34d399"
AMBER = "#fbbf24"
ROSE = "#fb7185"
TEXT_PRI = "#e2e8f0"
TEXT_SEC = "#64748b"
TEXT_DIM = "#475569"
class CustomDropdown(QWidget):
"""
完全自定义的下拉框组件,从根本上杜绝 QComboBox 原生系统的白边和虚线
"""
currentTextChanged = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self.items = []
self._current_text = ""
self.layout = QVBoxLayout(self)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setSpacing(0)
# 1. 触发按钮(伪装成 ComboBox 的显示区域)
self.btn = QPushButton()
self.btn.setStyleSheet(f"""
QPushButton {{
background-color: {BG_INPUT};
color: {TEXT_PRI};
border: 1px solid {BORDER_CLR};
border-radius: 8px;
padding: 5px 10px;
text-align: left;
font-size: 16px;
min-height: 32px;
outline: none;
}}
QPushButton:hover {{
border: 1px solid {CYAN};
}}
""")
self.btn.clicked.connect(self.show_popup)
self.layout.addWidget(self.btn)
# 2. 独立的下拉弹窗(使用 Qt.Popup 确保点击外部自动关闭)
self.popup = QWidget(self, Qt.Popup | Qt.FramelessWindowHint | Qt.NoDropShadowWindowHint)
self.popup.setAttribute(Qt.WA_TranslucentBackground) # 弹窗底层透明,杜绝直角白底
self.popup_layout = QVBoxLayout(self.popup)
self.popup_layout.setContentsMargins(0, 0, 0, 0)
self.popup_layout.setSpacing(0)
# 3. 弹窗里的列表控件
self.list_widget = QListWidget()
self.list_widget.setFocusPolicy(Qt.NoFocus) # 彻底杀死焦点虚线框
self.list_widget.setStyleSheet(f"""
QListWidget {{
background-color: {BG_CARD};
color: {TEXT_PRI};
border: 1px solid {BORDER_CLR};
border-radius: 8px;
outline: 0;
padding: 4px;
}}
QListWidget::item {{
border-radius: 4px;
padding: 8px;
color: {TEXT_PRI};
outline: none;
}}
QListWidget::item:hover, QListWidget::item:selected {{
background-color: {CYAN_DIM}; /* 悬浮颜色 */
color: white;
outline: none;
}}
""")
self.list_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.list_widget.itemClicked.connect(self.on_item_clicked)
self.popup_layout.addWidget(self.list_widget)
def addItem(self, text):
self.items.append(text)
self.list_widget.addItem(text)
if len(self.items) == 1:
self._current_text = text
self.btn.setText(text)
def removeItem(self, index):
if 0 <= index < len(self.items):
self.items.pop(index)
item = self.list_widget.takeItem(index)
if item:
del item
if self.items:
if self.currentIndex() == -1:
self.setCurrentIndex(max(0, index - 1))
else:
self._current_text = ""
self.btn.setText("")
self.currentTextChanged.emit("")
def currentText(self):
return self._current_text
def findText(self, text):
try:
return self.items.index(text)
except ValueError:
return -1
def setCurrentIndex(self, idx):
if 0 <= idx < len(self.items):
self._current_text = self.items[idx]
self.btn.setText(self._current_text)
self.currentTextChanged.emit(self._current_text)
def setCurrentText(self, text):
idx = self.findText(text)
if idx >= 0:
self.setCurrentIndex(idx)
def setItemText(self, idx, text):
if 0 <= idx < len(self.items):
old_text = self.items[idx]
self.items[idx] = text
item = self.list_widget.item(idx)
if item:
item.setText(text)
if self._current_text == old_text:
self._current_text = text
self.btn.setText(text)
def currentIndex(self):
try:
return self.items.index(self._current_text)
except ValueError:
return -1
def show_popup(self):
if not self.items: return
# 动态计算弹窗高度
item_height = 36
total_height = len(self.items) * item_height + 10
self.popup.resize(self.btn.width(), total_height)
# 获取按钮在屏幕上的全局坐标,将弹窗显示在按钮正下方
pos = self.btn.mapToGlobal(QPointF(0, self.btn.height() + 4).toPoint())
self.popup.move(pos)
self.popup.show()
def on_item_clicked(self, item):
self._current_text = item.text()
self.btn.setText(self._current_text)
self.popup.hide()
self.currentTextChanged.emit(self._current_text)
# ── 触感增强按钮基类 ────────────────────────────────────────
class TactileButton(QPushButton):
"""具有缩放和阴影反馈的触感增强按钮"""
def __init__(self, text="", parent=None, hover_color=CYAN):
super().__init__(text, parent)
self.setText(text)
self._hover_color = hover_color
self._is_pressed = False
# 阴影效果
self._shadow = QGraphicsDropShadowEffect(self)
self._shadow.setBlurRadius(15)
self._shadow.setColor(QColor(0, 0, 0, 150))
self._shadow.setOffset(0, 2)
self._shadow.setEnabled(False)
self.setGraphicsEffect(self._shadow)
def enterEvent(self, event):
self._shadow.setEnabled(True)
self._shadow.setColor(QColor(self._hover_color))
self._shadow.setBlurRadius(20)
super().enterEvent(event)
def leaveEvent(self, event):
self._shadow.setEnabled(False)
super().leaveEvent(event)
def mousePressEvent(self, event):
self._is_pressed = True
self._shadow.setOffset(0, 0)
self._shadow.setBlurRadius(10)
self.update()
super().mousePressEvent(event)
def mouseReleaseEvent(self, event):
self._is_pressed = False
self._shadow.setOffset(0, 2)
self._shadow.setBlurRadius(20)
self.update()
super().mouseReleaseEvent(event)
class ActionButton(TactileButton):
"""专用大操作按钮,带渐变色和强触感"""
def __init__(self, text, parent=None, color=CYAN, dim_color=CYAN_DIM):
super().__init__(text, parent, hover_color=color)
self._color = color
self._dim_color = dim_color
# ── 自定义发送按钮(向上箭头)────────────────────────────
class SendButton(TactileButton):
"""绘制向上箭头发送图标,增强触感"""
def __init__(self, parent=None):
super().__init__("", parent)
self.setObjectName("btn_send")
self.setFixedSize(42, 42)
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
w, h = self.width(), self.height()
# 背景
bg_color = QColor("#0e7490") if self._is_pressed else (QColor("#155e75") if self.underMouse() else QColor(CYAN_DIM))
p.setBrush(bg_color)
p.setPen(QPen(QColor(CYAN), 1) if self.underMouse() else Qt.NoPen)
p.drawRoundedRect(self.rect().adjusted(1,1,-1,-1), 10, 10)
# 偏移量模拟按下感
off = 2 if self._is_pressed else 0
cx, cy = w / 2.0, h / 2.0 + off
# 颜色
white = QColor("#ffffff")
if not self.isEnabled():
white = QColor(TEXT_DIM)
# 箭头杆(竖线)
pen = QPen(white, 3.0, Qt.SolidLine, Qt.RoundCap)
p.setPen(pen)
p.drawLine(QPointF(cx, cy + h * 0.22), QPointF(cx, cy - h * 0.18))
# 箭头头部(两条斜线)
tip_y = cy - h * 0.18
p.drawLine(QPointF(cx, tip_y), QPointF(cx - w * 0.18, tip_y + h * 0.16))
p.drawLine(QPointF(cx, tip_y), QPointF(cx + w * 0.18, tip_y + h * 0.16))
p.end()
# ── 自定义齿轮设置按钮 ────────────────────────────────────
class SettingsButton(QPushButton):
"""绘制齿轮图标的设置按钮,避免 emoji 在 Qt/Linux 上被裁剪"""
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(44, 44)
self.setStyleSheet(f"""
QPushButton {{ background: transparent; border: none; border-radius: 8px; }}
QPushButton:hover {{ background: {BG_CARD}; }}
QPushButton:pressed {{ background: {BG_INPUT}; }}
""")
def paintEvent(self, event):
super().paintEvent(event)
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
w, h = self.width(), self.height()
cx, cy = w / 2.0, h / 2.0 + (1 if self.isDown() else 0)
color = QColor(CYAN) if self.underMouse() else QColor(TEXT_SEC)
p.setPen(Qt.NoPen)
p.setBrush(color)
R = min(w, h) * 0.36 # 齿顶圆半径
ri = min(w, h) * 0.25 # 齿根圆半径
rc = min(w, h) * 0.12 # 中心孔半径
n = 8 # 齿数
tw = math.pi / n * 0.55 # 每齿半角宽
gear = QPainterPath()
for i in range(n):
base = 2 * math.pi * i / n
a1, a2 = base - tw, base + tw
a3 = base + tw + (math.pi / n - tw)
a4 = base + 2 * math.pi / n - tw - (math.pi / n - tw)
if i == 0:
gear.moveTo(cx + R * math.cos(a1), cy + R * math.sin(a1))
else:
gear.lineTo(cx + R * math.cos(a1), cy + R * math.sin(a1))
gear.lineTo(cx + R * math.cos(a2), cy + R * math.sin(a2))
gear.lineTo(cx + ri * math.cos(a3), cy + ri * math.sin(a3))
gear.lineTo(cx + ri * math.cos(a4), cy + ri * math.sin(a4))
gear.closeSubpath()
hole = QPainterPath()
hole.addEllipse(QPointF(cx, cy), rc, rc)
p.drawPath(gear.subtracted(hole))
p.end()
class CamLabel(QLabel):
"""相机显示标签:用 paintEvent 绘制图像,完全避免 setPixmap 触发 updateGeometry 导致布局跳变"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._cam_pixmap = None
def set_frame(self, pixmap):
"""替代 setPixmap,不触发布局重算"""
self._cam_pixmap = pixmap
self.update() # 只重绘,不重算布局
def paintEvent(self, event):
if self._cam_pixmap is None:
super().paintEvent(event)
return
p = QPainter(self)
scaled = self._cam_pixmap.scaled(
self.width(), self.height(),
Qt.KeepAspectRatio, Qt.SmoothTransformation)
x = (self.width() - scaled.width()) // 2
y = (self.height() - scaled.height()) // 2
p.drawPixmap(x, y, scaled)
p.end()
def sizeHint(self):
return QSize(640, 640)
def minimumSizeHint(self):
return QSize(320, 320)
class ChatInputEdit(QTextEdit):
"""支持自动变高、Shift+Enter换行、Enter发送的圆角输入框"""
send_requested = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.setPlaceholderText("输入自然语言指令...")
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setAcceptRichText(False)
self.setTabChangesFocus(False)
# 优化内部边距,文字居中且不被切断
self.document().setDocumentMargin(12)
# 初始高度(一行)
self.setFixedHeight(50)
self.textChanged.connect(self._adjust_height)
def _adjust_height(self):
# 强制更新文档宽度以计算高度
self.document().setTextWidth(self.viewport().width())
doc_height = self.document().size().height()
# 限制在 50px (1行) 到 160px (约5行) 之间
max_h = 160
new_height = max(50, min(max_h, int(doc_height) + 4))
if new_height != self.height():
self.setFixedHeight(new_height)
# 只有真正超过最大高度时才显示滚动条并取消隐藏样式
if doc_height > max_h - 10:
self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.verticalScrollBar().setStyleSheet("")
else:
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.verticalScrollBar().setStyleSheet("width: 0px; background: transparent;")
def keyPressEvent(self, event):
# Enter 发送,Shift+Enter 换行
if event.key() in (Qt.Key_Return, Qt.Key_Enter):
if event.modifiers() & Qt.ShiftModifier:
super().keyPressEvent(event)
else:
self.send_requested.emit()
else:
super().keyPressEvent(event)
# ── Toast 浮动通知 ────────────────────────────────────────
class Toast(QLabel):
"""短暂显示后渐隐的浮动通知"""
def __init__(self, parent, text, success=True):
super().__init__(text, parent)
bg = "#064e3b" if success else "#4c0519"
border = EMERALD if success else ROSE
self.setStyleSheet(f"""
QLabel {{ background: {bg}; color: {"#6ee7b7" if success else "#fda4af"};
border: 1px solid {border}; border-radius: 8px;
padding: 8px 18px; font-size: 13px; }}
""")
self.adjustSize()
pw, ph = parent.width(), parent.height()
self.move((pw - self.width()) // 2, ph - 80)
self.raise_()
self.show()
self._opacity = 1.0
self._timer = QTimer(self)
self._timer.timeout.connect(self._fade)
self._timer.start(40)
self._delay = 0
def _fade(self):
self._delay += 1
if self._delay < 40: # 等待约 1.6s 再开始渐隐
return
self._opacity -= 0.05
if self._opacity <= 0:
self._timer.stop()
self.deleteLater()
return
self.setWindowOpacity(self._opacity)
# QLabel 不支持 setWindowOpacity,用 stylesheet alpha 模拟
alpha = int(self._opacity * 255)
bg = f"rgba(6,78,59,{alpha})" if "6ee7b7" in self.styleSheet() else f"rgba(76,5,25,{alpha})"
clr = f"rgba(110,231,183,{alpha})" if "6ee7b7" in self.styleSheet() else f"rgba(253,164,175,{alpha})"
self.setStyleSheet(f"""
QLabel {{ background: {bg}; color: {clr};
border: 1px solid rgba(52,211,153,{alpha}); border-radius: 8px;
padding: 8px 18px; font-size: 13px; }}
""")
log_queue = queue.Queue()
result_queue = queue.Queue()
# ── 重定向 stdout/stderr ──────────────────────────────────
class QueueWriter(io.TextIOBase):
def __init__(self, q, tag="INFO"):
self.q, self.tag = q, tag
def write(self, text):
if text.strip():
self.q.put((self.tag, text.rstrip()))
return len(text)
def flush(self): pass
# ── 全局样式表(仅针对聊天区域进行字体缩放)────────────────────────
def build_stylesheet(chat_fs=16):
ui_fs = 13 # 固定其余 UI 元素的字号
return f"""
QMainWindow, QWidget {{ background: {BG_DARK}; color: {TEXT_PRI}; }}
QDialog {{ background: {BG_DARK}; color: {TEXT_PRI}; }}
QLabel {{ color: {TEXT_PRI}; background: transparent; font-size: {ui_fs}px; }}
QPushButton {{
background: {BG_CARD}; color: {TEXT_PRI};
border: 1px solid {BORDER_CLR}; border-radius: 8px;
padding: 6px 14px; font-size: {ui_fs + 1}px;
}}
/* 针对聊天气泡和输入框使用动态字号 */
QLabel#chat_bubble_user, QLabel#chat_bubble_ai, ChatInputEdit {{
font-size: {chat_fs}px;
}}
QLineEdit {{
background: {BG_INPUT}; color: {TEXT_PRI};
border: 1px solid {BORDER_CLR}; border-radius: 20px;
padding: 6px 16px; font-size: {ui_fs}px;
}}
QTextEdit {{
background: {BG_INPUT}; color: {TEXT_PRI};
border: 1px solid {BORDER_CLR}; border-radius: 22px;
padding: 0px 16px;
}}
QPushButton:hover {{
background: {BG_INPUT};
border-color: {CYAN};
color: white;
}}
QPushButton:pressed {{
background: {BG_DARK};
padding-top: 8px;
padding-left: 16px;
}}
QPushButton:disabled {{ color: {TEXT_DIM}; border-color: {BORDER_CLR}; background: {BG_DARK}; }}
QPushButton#btn_exec {{
background: {CYAN_DIM}; color: {CYAN};
border: 1px solid {CYAN_DIM}; font-weight: bold;
border-radius: 10px;
}}
QPushButton#btn_exec:hover {{ background: #155e75; border-color: {CYAN}; color: white; }}
QPushButton#btn_exec:pressed {{ background: #0e7490; padding-top: 10px; }}
QPushButton#btn_stop {{
background: {BG_INPUT}; color: {TEXT_SEC};
border: 1px solid {BORDER_CLR}; border-radius: 10px;
}}
QPushButton#btn_stop:hover {{ background: #3f1219; color: {ROSE}; border-color: {ROSE}; }}
QPushButton#btn_stop:pressed {{ background: #5a1a24; padding-top: 10px; }}
QPushButton#btn_sparkle {{
background: {INDIGO_DIM}; color: {INDIGO};
border: 1px solid #4338ca; border-radius: 10px;
}}
QPushButton#btn_sparkle:hover {{ background: #3730a3; border-color: {INDIGO}; color: white; }}
QPushButton#btn_sparkle:pressed {{ background: #4338ca; padding-top: 2px; }}
QLineEdit:focus, QTextEdit:focus {{ border-color: {CYAN_DIM}; }}
QScrollArea {{ border: none; background: transparent; }}
QScrollBar:vertical {{ background: {BG_PANEL}; width: 6px; border-radius: 3px; }}
QScrollBar::handle:vertical {{ background: {BORDER_CLR}; border-radius: 3px; min-height: 20px; }}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{ height: 0; }}
QComboBox {{
background: {BG_INPUT}; color: {TEXT_PRI};
border: 1px solid {BORDER_CLR}; border-radius: 8px;
padding: 6px 10px; font-size: {ui_fs}px;
}}
QComboBox::drop-down {{ border: none; }}
QComboBox QAbstractItemView {{
background: {BG_CARD}; color: {TEXT_PRI};
border: 1px solid {BORDER_CLR};
selection-background-color: {CYAN_DIM};
outline: none; font-size: {ui_fs}px; padding: 2px;
}}
QRadioButton {{ color: {TEXT_PRI}; spacing: 8px; font-size: {ui_fs}px; }}
QRadioButton::indicator {{
width: 14px; height: 14px; border-radius: 7px;
border: 2px solid {TEXT_SEC}; background: transparent;
}}
QRadioButton::indicator:checked {{ background: {CYAN}; border-color: {CYAN}; }}
QSplitter::handle {{ background: {BG_DARK}; border: none; }}
QSplitter::handle:horizontal {{ width: 4px; }}
QSplitter::handle:vertical {{ height: 4px; }}
QSplitter::handle:hover {{ background: {CYAN_DIM}; }}
"""
# ── 线程信号(线程安全 UI 更新)────────────────────────────
class UISignals(QObject):
add_chat = pyqtSignal(str, str) # text, side
add_log = pyqtSignal(str, str) # tag, msg
update_cam = pyqtSignal(str, object) # key, bgr_img
task_done = pyqtSignal()
set_status = pyqtSignal(str) # ready|running|error
set_scene_status = pyqtSignal(str) # scene name
plan_done = pyqtSignal(bool, str) # ok, result
# ── 设置读写(从 config.py 读取,保存也写回 config.py)──────
def load_settings():
try:
from config import Config
models = {k: dict(v) for k, v in Config.MODELS.items()}
active = Config.ACTIVE_MODEL
font_size = getattr(Config, 'UI_FONT_SIZE', 13)
except Exception:
models = {"qwen-vl-max-latest": {
"url": "https://dashscope.aliyuncs.com/compatible-mode/v1", "key": ""}}
active = "qwen-vl-max-latest"
font_size = 13
if active not in models:
active = next(iter(models), "")
m = models.get(active, {})
return {
"models": models, "current_model": active,
"api_url": m.get("url", ""), "api_key": m.get("key", ""),
"model_name": active, "font_size": font_size,
}
def save_to_config(models: dict, active_model: str, font_size: int = 13):
"""将模型列表和当前选择写回 config.py,其余配置保持不变"""
config_path = os.path.join(ROOT_DIR, "config.py")
try:
from config import Config
# 构建 MODELS 字符串
m_lines = ["{\n"]
for name, info in models.items():
m_lines.append(f" {repr(name)}: {{\n")
m_lines.append(f" 'url': {repr(info.get('url', ''))},\n")
m_lines.append(f" 'key': {repr(info.get('key', ''))},\n")
m_lines.append(f" }},\n")
m_lines.append(" }")
models_repr = "".join(m_lines)
polish_key = repr(Config.POLISH_API_KEY)
polish_url = repr(Config.POLISH_BASE_URL)
polish_model= repr(Config.POLISH_MODEL)
content = f'''"""
全局配置文件 - 统一管理 API Keys、模型名称、URL 等
"""
class Config:
# ==================== 润色专用模型(不在 UI 设置中显示)====================
POLISH_API_KEY = {polish_key}
POLISH_BASE_URL = {polish_url}
POLISH_MODEL = {polish_model}
# ==================== 用户可配置模型列表(UI 设置中管理)====================
MODELS = {models_repr}
ACTIVE_MODEL = {repr(active_model)}
# ==================== 模型参数 ====================
DEFAULT_TEMPERATURE = {getattr(Config, 'DEFAULT_TEMPERATURE', 0.1)}
DISABLE_PROXY = {getattr(Config, 'DISABLE_PROXY', True)}
UI_FONT_SIZE = {font_size}
CAMERA_FPS = {getattr(Config, 'CAMERA_FPS', 15)}
LOG_AUTOSCROLL = {getattr(Config, 'LOG_AUTOSCROLL', True)}
# ==================== 机械臂工作空间 ====================
ROBOT_BASE_X = {getattr(Config, 'ROBOT_BASE_X', 1.1)}
ROBOT_BASE_Y = {getattr(Config, 'ROBOT_BASE_Y', 0.3)}
WORKSPACE_R_MIN = {getattr(Config, 'WORKSPACE_R_MIN', 0.15)}
WORKSPACE_R_MAX = {getattr(Config, 'WORKSPACE_R_MAX', 0.82)}
TABLE_X_MIN = {getattr(Config, 'TABLE_X_MIN', 0.0)}
TABLE_X_MAX = {getattr(Config, 'TABLE_X_MAX', 1.6)}
TABLE_Y_MIN = {getattr(Config, 'TABLE_Y_MIN', 0.0)}
TABLE_Y_MAX = {getattr(Config, 'TABLE_Y_MAX', 1.2)}
@classmethod
def get_qwen_client_config(cls):
"""获取当前激活模型的配置"""
active_config = cls.MODELS.get(cls.ACTIVE_MODEL)
if not active_config:
raise ValueError(f"未找到模型配置: {{cls.ACTIVE_MODEL}}")
return {{
'api_key': active_config.get('key', ''),
'base_url': active_config.get('url', '')
}}
@classmethod
def create_qwen_client(cls):
"""创建使用当前激活模型配置的客户端"""
from openai import OpenAI
import httpx
config = cls.get_qwen_client_config()
return OpenAI(
api_key=config['api_key'],
base_url=config['base_url'],
http_client=httpx.Client(trust_env=False)
)
@classmethod
def get_active_model_name(cls):
"""获取当前激活的模型名称"""
return cls.ACTIVE_MODEL
@classmethod
def validate(cls):
"""验证当前激活模型的配置是否有效"""
if not cls.ACTIVE_MODEL:
raise ValueError("未设置 ACTIVE_MODEL")
if cls.ACTIVE_MODEL not in cls.MODELS:
raise ValueError(f"ACTIVE_MODEL '{{cls.ACTIVE_MODEL}}' 不在 MODELS 列表中")
config = cls.MODELS[cls.ACTIVE_MODEL]
if not config.get('key'):
raise ValueError(f"模型 '{{cls.ACTIVE_MODEL}}' 缺少 API Key")
if not config.get('url'):
raise ValueError(f"模型 '{{cls.ACTIVE_MODEL}}' 缺少 API URL")
return True
'''
with open(config_path, "w") as f:
f.write(content)
# 重新加载配置模块
import importlib, sys as _sys
if 'config' in _sys.modules:
importlib.reload(_sys.modules['config'])
# 强制重新加载 vlm_process 模块以使用新配置
if 'vlm_process' in _sys.modules:
importlib.reload(_sys.modules['vlm_process'])
print(f"[save_to_config] 配置已保存并重新加载,当前模型: {active_model}", flush=True)
except Exception as e:
print(f"[save_to_config] 失败: {e}", flush=True)
raise
# ── 辅助:创建分隔线 ──────────────────────────────────────
def make_separator(horizontal=True):
line = QFrame()
line.setFrameShape(QFrame.HLine if horizontal else QFrame.VLine)
line.setStyleSheet(f"color: {BORDER_CLR}; background: {BORDER_CLR};")
line.setFixedHeight(1) if horizontal else line.setFixedWidth(1)
return line
# ── 辅助:创建卡片容器 ────────────────────────────────────
def make_card(parent=None):
w = QWidget(parent)
w.setStyleSheet(f"""
QWidget {{
background: {BG_CARD};
border: 1px solid {BORDER_CLR};
border-radius: 10px;
}}
""")
return w
# ── 辅助:节标题 Label ────────────────────────────────────
def make_section_label(text, parent=None):
lbl = QLabel(text, parent)
lbl.setStyleSheet(f"color: {TEXT_SEC}; font-size: 19px; font-weight: bold;"
f" background: transparent; border: none;")
return lbl
# ══════════════════════════════════════════════════════════
# 主窗口
# ══════════════════════════════════════════════════════════
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("机器人智能抓取平台")
self.resize(1720, 1000)
self.setMinimumSize(1280, 800)
# ── 状态 ──
self.status = "ready"
self.running = False
self.env = None
self.env_ready = False
self._task_queue = queue.Queue()
self._scene_switch_queue = queue.Queue()
self._log_buffer = []
self._chat_mode = "normal"
self._clarification_event = threading.Event()
self._clarification_result = None
self._settings = load_settings()
self.is_planning = False
self.is_diagnosing = False
self.current_scene_name = "普通场景"
self.current_scene_path = "/home/robot/VLM_Grasp_Bio-UI/manipulator_grasp/assets/scenes/scene.xml"
# ── 信号 ──
self.sig = UISignals()
self.sig.add_chat.connect(self._add_chat_bubble)
self.sig.add_log.connect(self._append_log)
self.sig.update_cam.connect(self._update_camera)
self.sig.task_done.connect(self._on_task_done)
self.sig.set_status.connect(self._set_status)
self.sig.set_scene_status.connect(self._set_scene_status)
self.sig.plan_done.connect(self._on_plan_done)
self._build_ui()
# 轮询定时器
self._timer = QTimer(self)
self._timer.timeout.connect(self._poll_queues)
self._timer.start(50)
# 欢迎消息
self._add_chat_bubble("机器人智能抓取平台已启动。", "system")
self._add_chat_bubble(
"您好!我是智能视觉抓取助手。您可以直接下发操作指令,"
"或者输入初步想法并点击 ✨ 按钮,我会为您将其转化为精准的机器人执行命令。", "ai")
# 启动 MuJoCo 线程
threading.Thread(target=self._mujoco_loop, daemon=True).start()
# ══════════════════════════════════════════════════════
# 构建 UI
# ══════════════════════════════════════════════════════
def _build_ui(self):
central = QWidget()
self.setCentralWidget(central)
root_layout = QVBoxLayout(central)
root_layout.setContentsMargins(0, 0, 0, 0)
root_layout.setSpacing(0)
root_layout.addWidget(self._build_header())
# ── 1. 创建左右中的三个面板 ──
left_p = self._build_left_panel()
center_p = self._build_center_panel()
right_p = self._build_right_panel()
# ── 2. 设置最小宽度,防止被挤没 ──
left_p.setMinimumWidth(220)
center_p.setMinimumWidth(500)
right_p.setMinimumWidth(280)
# ── 3. 使用 QSplitter 实现主布局 ──
self.main_splitter = QSplitter(Qt.Horizontal)
self.main_splitter.setHandleWidth(6)
self.main_splitter.addWidget(left_p)
self.main_splitter.addWidget(center_p)
self.main_splitter.addWidget(right_p)
# ── 4. 禁止折叠(最重要:防止拖动时消失) ──
self.main_splitter.setCollapsible(0, False)
self.main_splitter.setCollapsible(1, False)
self.main_splitter.setCollapsible(2, False)
# 设置伸缩权重,中间区域最灵活
self.main_splitter.setStretchFactor(0, 0)
self.main_splitter.setStretchFactor(1, 1)
self.main_splitter.setStretchFactor(2, 0)
# 初始尺寸分配
self.main_splitter.setSizes([250, 1220, 250])
# 延迟再次设置尺寸,确保在窗口显示后布局生效,解决“初始窄”的问题
QTimer.singleShot(200, lambda: self.main_splitter.setSizes([250, 1220, 250]))
body_wrapper = QWidget()
body_lay = QVBoxLayout(body_wrapper)
body_lay.setContentsMargins(8, 6, 8, 8)
body_lay.addWidget(self.main_splitter)
root_layout.addWidget(body_wrapper, 1)
def _build_header(self):
hdr = QWidget()
hdr.setFixedHeight(50)
hdr.setStyleSheet(f"background: {BG_PANEL}; border-bottom: 1px solid {BORDER_CLR};")
lay = QHBoxLayout(hdr)
lay.setContentsMargins(16, 0, 16, 0)
logo = QLabel("🤖")
logo.setStyleSheet(f"color: {CYAN}; font-size: 20px; font-weight: bold;")
title = QLabel("机器人智能抓取平台")
title.setStyleSheet("font-size: 20px; font-weight: bold;")
lay.addWidget(logo)
lay.addWidget(title)
lay.addStretch()
self.status_dot = QLabel("●")
self.status_dot.setStyleSheet(f"color: {EMERALD}; font-size: 20px;")
self.status_label = QLabel("系统就绪")
self.status_label.setStyleSheet(f"color: {EMERALD}; font-size: 20px;")
lay.addWidget(self.status_dot)
lay.addWidget(self.status_label)
lay.addSpacing(16)
btn_settings = SettingsButton()
btn_settings.clicked.connect(self._open_settings)
lay.addWidget(btn_settings)
return hdr
def _build_left_panel(self):
panel = QWidget()
panel.setMinimumWidth(220)
panel.setStyleSheet(f"background: {BG_PANEL}; border: 1px solid {BORDER_CLR}; border-radius: 12px;")
lay = QVBoxLayout(panel)
lay.setContentsMargins(8, 8, 8, 8)
lay.setSpacing(6)
# 场景切换
scene_card = make_card()
scene_lay = QVBoxLayout(scene_card)
scene_lay.setContentsMargins(10, 10, 10, 10)
scene_lay.addWidget(make_section_label("🔄 场景模式"))
# 场景选择下拉框
scene_label = QLabel("当前场景:")
scene_label.setStyleSheet(f"color: {TEXT_SEC}; font-size: 14px; background: transparent; border: none;")
scene_lay.addWidget(scene_label)
self.scene_combo = CustomDropdown()
self.scene_combo.addItem("普通场景")
self.scene_combo.addItem("障碍场景")
self.scene_combo.setCurrentIndex(0)
self.scene_combo.currentTextChanged.connect(self._on_scene_changed)
scene_lay.addWidget(self.scene_combo)
# 场景状态指示
self.scene_status_label = QLabel("✓ 普通场景已加载")
self.scene_status_label.setStyleSheet(f"color: {EMERALD}; font-size: 13px; background: transparent; border: none; padding: 4px;")
scene_lay.addWidget(self.scene_status_label)
# 规划算法选择
planner_label = QLabel("路径规划:")
planner_label.setStyleSheet(f"color: {TEXT_SEC}; font-size: 14px; background: transparent; border: none;")
scene_lay.addWidget(planner_label)
self.planner_combo = CustomDropdown()
self.planner_combo.addItem("默认算法")
self.planner_combo.addItem("RRT避障算法")
self.planner_combo.setCurrentIndex(0)
scene_lay.addWidget(self.planner_combo)
lay.addWidget(scene_card)
# 快捷控制
ctrl = make_card()
ctrl_lay = QVBoxLayout(ctrl)
ctrl_lay.setContentsMargins(10, 10, 10, 10)
ctrl_lay.addWidget(make_section_label("⚡ 快捷控制"))
self.btn_exec = ActionButton("▶️ 执行任务", color=CYAN, dim_color=CYAN_DIM)
self.btn_exec.setObjectName("btn_exec")
self.btn_exec.setFixedHeight(38)
self.btn_exec.clicked.connect(self._on_execute)
self.btn_stop = ActionButton("⏹️ 紧急停止", color=ROSE, dim_color=BG_INPUT)
self.btn_stop.setObjectName("btn_stop")
self.btn_stop.setFixedHeight(38)
self.btn_stop.setEnabled(False)
self.btn_stop.clicked.connect(self._on_stop)
ctrl_lay.addWidget(self.btn_exec)
ctrl_lay.addWidget(self.btn_stop)
lay.addWidget(ctrl)
# 快捷指令
ex_card = make_card()
ex_lay = QVBoxLayout(ex_card)
ex_lay.setContentsMargins(10, 10, 10, 10)
ex_lay.addWidget(make_section_label("💻 快捷指令"))
examples = ["把培养皿放到显微镜右边",
"把培养皿放回货架",
"把培养皿放到显微镜左边一点",
"把培养皿放到绿色区域左边4厘米",
"把培养皿放回上次的位置",
"把鸭子放到显微镜左边"]
for ex in examples:
btn = QPushButton(ex)
btn.setStyleSheet(f"""
QPushButton {{
background: {BG_DARK}; color: {TEXT_PRI};
border: 1px solid {BORDER_CLR}; border-radius: 8px;
padding: 6px 10px; font-size: 18px; text-align: left;
}}
QPushButton:hover {{
background: {CYAN_DIM}; border-color: {CYAN_DIM};
color: {CYAN};
}}
""")
btn.clicked.connect(lambda _, t=ex: self._fill_input(t))
ex_lay.addWidget(btn)
ex_lay.addStretch(1)
ex_lay.addWidget(make_separator())
btn_log = QPushButton("📋 查看底层调试日志")
btn_log.setStyleSheet(f"""
QPushButton {{
background: transparent; color: {TEXT_SEC};
border: 1px solid {BORDER_CLR}; border-radius: 8px;
padding: 8px; font-size: 18px;
}}
QPushButton:hover {{
background: {CYAN_DIM}; color: {CYAN};
border-color: {CYAN_DIM};
}}
""")
btn_log.clicked.connect(self._open_log_dialog)
ex_lay.addWidget(btn_log)
lay.addWidget(ex_card, 1)
return panel
def _build_center_panel(self):
# ── 相机区域始终保持 50/50 比例 ──
container = QWidget()
container.setStyleSheet("background: transparent; border: none;")
lay = QHBoxLayout(container)
lay.setContentsMargins(0, 0, 0, 0)
lay.setSpacing(6)
for key, label, color in [
("cam1", "● 物品观测区域", CYAN),
("cam2", "● 物品放置区", EMERALD)