场景:
有两个QLineEdit控件,记录用户选择的目录,当用户在QLineEdit控件上右击时,显示右键菜单->浏览目录,点击“浏览目录”时通过资源管理器打开目录。
import os import subprocess import sys from PyQt5.QtGui import QIcon, QCursor, QPixmap from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QFileDialog, QMenu from PyQt5.QtCore import Qt from main_window import Ui_frmMain from appConfig import Config import files_rc
def __init__(self): super().__init__() self.createContextMenu(self.txtOutputImagesDir) self.createContextMenu(self.txtOutputVideoDir) def createContextMenu(self, ctl): try: ctl.setContextMenuPolicy(Qt.CustomContextMenu) ctl.customContextMenuRequested.connect(lambda: self.showContextMenu(ctl)) # 创建QMenu ctl.contextMenu = QMenu(ctl) # icon3 = QIcon() # icon3.addPixmap(QPixmap(":/16x16/icons/16x16/cil-folder-open.png"), QIcon.Normal, QIcon.Off) action = ctl.contextMenu.addAction(QIcon(":/16x16/icons/16x16/cil-folder-open.png"), u'浏览目录') action.triggered.connect(lambda: self.action_open_directory_Handler(ctl)) except Exception as ex: print(ex) def showContextMenu(self, ctl): ''''' 右键点击显示控件右键菜单 ''' # 菜单定位 ctl.contextMenu.exec_(QCursor.pos()) def action_open_directory_Handler(self, ctl): ''''' 控件右键菜单对应的action ''' dir = ctl.text() if len(dir) == 0: return try: os.startfile(dir) except Exception as ex: subprocess.Popen(['xdg-open', dir])