1
votes

I'd like to subclass QTextEdit so that the user can change a text selection by moving either side of the selection using shift-click. Right now, shift-click does not permit the anchor to move. The first step, I believe is to override the default shift-click functionality. I've tried to do this using a mousePressEvent and also a mouseMoveEvent, but neither event triggers when I shift-click and move the mouse. How can I detect the shift-click drag currently used to modify the selection? My code is below.

I vaguely remember reading that within a mouseMoveEvent, buttons equals "none". I cannot find that reference now though. If this is true, I'm even more perplexed.

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_())
1

1 Answers

1
votes

The problem is that you don't call the QMouseEvent.buttons method, you are comparing a method with the numeric value of Qt.LeftButton.

You must do:

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