File size: 2,151 Bytes
06bc836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ui.py
from PySide6.QtWidgets import QWidget, QLabel, QVBoxLayout
from PySide6.QtCore import Qt
import win32gui

class CandidateWindow(QWidget):
    def __init__(self):
        super().__init__()
        
        # 窗口属性:置顶、无边框、不抢占焦点
        self.setWindowFlags(
            Qt.Tool | 
            Qt.FramelessWindowHint | 
            Qt.WindowStaysOnTopHint | 
            Qt.WindowDoesNotAcceptFocus
        )
        self.setAttribute(Qt.WA_TranslucentBackground)
        
        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        
        self.label = QLabel("")
        self.label.setStyleSheet("""

            QLabel {

                background-color: rgba(40, 44, 52, 240);

                color: #abb2bf;

                font-family: "Microsoft YaHei UI";

                font-size: 18px;

                padding: 8px 15px;

                border: 1px solid #61afef;

                border-radius: 6px;

            }

        """)
        self.layout.addWidget(self.label)

    def get_caret_pos(self):
        """尝试获取光标位置"""
        try:
            gui_info = win32gui.GetGUIThreadInfo(0)
            hwnd = gui_info['hwndFocus']
            rect = gui_info['rcCaret']
            # 将客户端坐标转为屏幕坐标
            p = win32gui.ClientToScreen(hwnd, (rect[0], rect[1]))
            return p[0], p[1]
        except:
            return None

    def update_candidates(self, candidates):
        if not candidates:
            self.hide()
            return

        # 格式化显示:1.词 A  2.词 B
        items = [f"<span style='color:#61afef;'>{i+1}.</span>{c}" for i, c in enumerate(candidates)]
        self.label.setText(f"<html>{'&nbsp;&nbsp;'.join(items)}</html>")
        self.adjustSize()

        pos = self.get_caret_pos()
        if pos:
            self.move(pos[0], pos[1] + 28) # 移动到光标下方
        else:
            # 备选方案:显示在鼠标附近或屏幕中心
            pass
        
        self.show()
        self.raise_()