gpt4 book ai didi

python - 使用 Python 检测 QTextEdit 中的 Shift-Click 拖动

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:50 24 4
gpt4 key购买 nike

我想对 QTextEdit 进行子类化,以便用户可以通过使用 Shift 键并单击移动选择的任一侧来更改文本选择。现在,按住 Shift 键并单击不允许 anchor 移动。我认为第一步是覆盖默认的 Shift 键单击功能。我尝试使用 mousePressEvent 和 mouseMoveEvent 来执行此操作,但是当我按住 Shift 键并单击并移动鼠标时,这两个事件都不会触发。如何检测当前用于修改选择的按住 Shift 键并单击的拖动?我的代码如下。

我依稀记得读过,在 mouseMoveEvent 中,按钮等于“无”。但我现在找不到该引用资料。如果这是真的,我就更困惑了。

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class TextEditor(QTextEdit):

def __init__(self, parent=None, text=None):
super().__init__(parent)
self.setReadOnly(True)
self.setText(text)
self.setMouseTracking(True) # Not sure if I will need this

def mousePressEvent(self, event):
if event.buttons==Qt.LeftButton:
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ShiftModifier:
print("Shift+Left Click") # This never triggers
super().mousePressEvent(event)

def mouseMoveEvent(self, event):
if event.buttons==Qt.LeftButton:
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ShiftModifier:
print("Move and Shift + Left Button") # This never triggers
super().mouseMoveEvent(event)

if __name__ == '__main__':
app = QApplication(sys.argv)
window = TextEditor(text="Faction leaders unanimously decided to form a parliamentary inquiry committee...")
window.show()

sys.exit(app.exec_())

最佳答案

问题是您没有调用 QMouseEvent.buttons 方法,而是将方法与 Qt.LeftButton 的数值进行比较。

你必须这样做:

if event.buttons() == Qt.LeftButton:
# ^^

关于python - 使用 Python 检测 QTextEdit 中的 Shift-Click 拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46872850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com