Python PyQt5。如何在与ContextMenu连接的QTextEdit中获取光标位置?
我尝试在Python PyQt5。如何在与ContextMenu连接的QTextEdit中获取光标位置?,python,pyqt,pyqt5,Python,Pyqt,Pyqt5,我尝试在QTextEdit中获取光标位置: class CustomEdit(QTextEdit): def __init__(self): super(CustomEdit, self).__init__() self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.cursor = self.textCursor() self.menu = None s
QTextEdit
中获取光标位置:
class CustomEdit(QTextEdit):
def __init__(self):
super(CustomEdit, self).__init__()
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.cursor = self.textCursor()
self.menu = None
self.customContextMenuRequested.connect(self.create_menu)
def create_menu(self, pos):
self.menu = QMenu()
self.menu.addSeparator()
func = self.menu.addAction(u'function')
action = self.menu.exec_(self.viewport().mapToGlobal(pos))
if action == func:
self.func()
def func(self)
print(self.cursor.positionInBlock())
但它不起作用。它返回了与光标位置不相关的错误数字。我从项目中正确复制过去。Self-它是该函数的参数,作为从QTextEdit@eyllanesc,pyqt5光标在块中的相对位置我通过
PySide
尝试了您的代码,我可以在qtexedit
上显示上下文菜单。如果用鼠标右键单击,上下文菜单将在该位置弹出,对吗?positionInBlock()
返回了0