【问题标题】:PyQt5. How to get cursor position in QTextEdit connected with ContextMenu?PyQt5。如何在与 ContextMenu 连接的 QTextEdit 中获取光标位置?
【发布时间】:2019-01-04 17:03:27
【问题描述】:

我尝试在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 尝试了你的代码,我可以在QTextEdit 上显示上下文菜单。如果你用鼠标右键单击,上下文菜单会在该位置弹出,对吗?positionInBlock()返回 0

标签: python pyqt pyqt5


【解决方案1】:

有点晚了,但我也在找这个,发现你可以使用self.QTextEdit.textCursor().position() 来获取光标位置的整数。

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
  • 2022-10-07
  • 1970-01-01
相关资源
最近更新 更多