在 PySide6(或 PyQt)中,默认情况下 QMenu 的动作文本不支持 HTML 富文本。如果你想使用富文本格式,你需要使用自定义的 QLabel 小部件来实现。
下面是一个使用 QLabel 作为动作项的示例:
from PySide6.QtWidgets import QApplication, QMainWindow, QMenu, QLabel, QAction
from PySide6.QtGui import QCursor
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('右键菜单示例')
self.setGeometry(100, 100, 600, 400)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.context_MenuEvent)
def context_MenuEvent(self, event): # 右键菜单
context_menu = QMenu(self)
color_del = context_menu.addAction('删除 | 标记')
for i in range(5): # 假设 i 的范围是 0 到 4
myselect_menu = context_menu.addAction(f"标记 | {i}")
myselect_menu.triggered.connect(self.code_tag)
# 使用QLabel实现富文本
label = QLabel()
label.setText("删除 | <b>自选</b>")
action = QWidgetAction(self)
action.setDefaultWidget(label)
context_menu.addAction(action)
# 显示菜单
context_menu.exec_(QCursor.pos())
def code_tag(self):
# 这里实现你的标记逻辑
print("标记被点击")
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
这种方法利用 QLabel 设置富文本内容,然后将其包装在 QWidgetAction 中添加到菜单中。
你可以根据需要进行调整,确保符合作用。希望这能解决你的问题!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |