PyQt - sellectAll then Backspace to delete doesn't work - python

I have a text editor which converts latin keybord keypresses to russian characters. I have reimplemented a QTextEdit class:
class MyTextEdit(QTextEdit):
def __init__(self, *args):
QTextEdit.__init__(self, *args)
leftMousePressedSignal = pyqtSignal(QPoint)
rightMousePressedSignal = pyqtSignal(QPoint, QEvent)
mouseMovedSignal = pyqtSignal(QPoint)
mouseDoubleClickedSignal = pyqtSignal(QPoint)
keyPressedSignal = pyqtSignal(QEvent)
def mousePressEvent(self, event):
pos = event.pos()
if event.button() == Qt.LeftButton:
self.leftMousePressedSignal.emit(pos)
elif event.button() == Qt.RightButton:
self.rightMousePressedSignal.emit(pos, event)
def mouseMoveEvent(self, event):
if event.buttons() & Qt.LeftButton:
pos = event.pos()
self.mouseMovedSignal.emit(pos)
def mouseDoubleClickEvent(self, event):
if event.button() == Qt.LeftButton:
pos = event.pos()
self.mouseDoubleClickedSignal.emit(pos)
def keyPressEvent(self, event):
if event.type() == QEvent.KeyPress:
self.keyPressedSignal.emit(event)
which I then use with the reimplemented keyPressEvent. So I had to reimplement the Backspace action as well:
self.textEdit = MyTextEdit(self)
...
self.textEdit.keyPressedSignal.connect(self.OnKeyPressed)
self.actionSelectAll.triggered.connect(self.textEdit.selectAll)
...
def OnKeyPressed(self, event):
key = event.key()
txt = str(event.text())
if key == Qt.Key_Backspace:
if self.cursor.hasSelection():
self.cursor.movePosition(QTextCursor.NoMove, QTextCursor.KeepAnchor, self.cursor.selectionStart() - self.cursor.selectionStart())
else:
self.cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor, 1)
self.textEdit.setTextCursor(self.cursor)
self.textEdit.cut()
elif key == Qt.Key_A and (event.modifiers() & Qt.ControlModifier):
self.textEdit.selectAll()
Now, if nothing's selected and I press Backspace, it deletes a single character to the left of the cursor. When a word is selected with a mouse and I press Backspace, it deletes the word. When a few words or the whole text is selected with the mouse and I press Backspace, it deletes the whole selection. So, it works fine. When I press a Select All button (or Ctrl+A) - it selects the whole text. But if I then press Backspace it only deletes 1 character to the left of the cursor, not the whole text.
I will greatly appreciate it if you cold tell me what I'm doing wrong here. Thank you.

Why are you reimplimenting selection and deleting behaviour, and why it's done not in MyTextEdit? If you just need to
convert latin keybord keypresses to russian characters
you can only do this conversion, and let other work (selection, deliting, copying, etc) for QTextEdit.
I'd write it like this:
class TransliterationEdit(QTextEdit):
latin_alphabet = unicode(string.ascii_letters) # or dict with transliteration table
def translateLetter(self, letter):
return u'Ъ' # just example, you need translate letter somehow
def keyPressEvent(self, event):
text = unicode(event.text())
if text and text in self.latin_alphabet:
self.insertPlainText(self.translateLetter(text))
event.ignore()
else:
QTextEdit.keyPressEvent(self, event)
UPDATE
Here's my rough implementation of TextEdit which converts Latin keypresses to Russian characters, hope it will help.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtGui import *
from transliterator import SMTransliterator
# transliterator available at https://gist.github.com/1600988
class TransliterationEdit(QTextEdit):
def __init__(self, *args, **kwargs):
QTextEdit.__init__(self, *args, **kwargs)
self._transliterator = SMTransliterator()
def keyPressEvent(self, event):
text = unicode(event.text())
if not self._transliterator.add_letter(text):
if text and self._transliterator.result:
self.insertPlainText(self._transliterator.result)
return QTextEdit.keyPressEvent(self, event)
if self._transliterator.need_next:
return # skip it
self.insertPlainText(self._transliterator.result)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = TransliterationEdit()
window.show()
sys.exit(app.exec_())
transliterator available at gist

Related

copy/select text in WhatsThis

Example:
class tab_1(QWidget):
def __init__(self):
super(tab_1, self).__init__()
self.initUI()
def initUI(self):
self.btn = QPushButton(self)
self.btn.setText("tab1")
self.btn.setWhatsThis(
"""''(parameter) self: ~tab
Sourcery Code Metrics
Complexity 0 ⭐
Size 108 🙂
Working Memory 4 ⭐
Quality Score 82 % ⭐
⟠ self: [tab] Docc"""
""
)
I use the setWhatsThis and try to copy/select the text of it, but
when I click the mouse
In WhatsThis area is Disappear!
Example
In general, the what's this behavior is to only handles clicks on hyperlinks (which normally launch the application help dialog), so if the user clicks it, it will automatically close anyway.
The only solution is to override the default behavior by mimicking what Qt normally does: install an event filter on the application whenever a top level window receives a EnterWhatsThisMode event type, and create a custom widget that is shown whenever it's appropriate.
Since this will cause to override all what's this cases, I'd suggest to also set the WA_CustomWhatsThis attribute for the widgets that will have selectable text, so that you can use the standard behavior for any other case.
The custom widget is actually a QLabel with the Popup window flag set, which will make the widget a top level window that also captures mouse events, and with the TextSelectableByMouse and LinksAccessibleByMouse text interaction flags set.
class SelectableWhatsThis(QtWidgets.QLabel):
def __init__(self, parent, pos):
super().__init__(parent.whatsThis(), parent, flags=QtCore.Qt.Popup)
self.setTextInteractionFlags(
QtCore.Qt.TextSelectableByMouse | QtCore.Qt.LinksAccessibleByMouse)
self.setBackgroundRole(QtGui.QPalette.ToolTipBase)
self.setForegroundRole(QtGui.QPalette.ToolTipText)
self.setAutoFillBackground(True)
self.setContentsMargins(12, 8, 12, 8)
self.move(pos)
self.show()
def mousePressEvent(self, event):
if event.pos() not in self.rect():
self.close()
else:
super().mousePressEvent(event)
def keyPressEvent(self, event):
self.close()
class WhatsThisHelper(QtCore.QObject):
installed = active = False
whatsThis = None
def __init__(self, parent):
super().__init__(parent)
if not self.installed:
# ensure that only one instance of WhatsThisHelper is installed
self.__class__.installed = True
QtWidgets.QApplication.instance().installEventFilter(self)
self.active = True
def eventFilter(self, obj, event):
if not obj.isWidgetType():
return False
if (event.type() == event.MouseButtonPress
and event.button() == QtCore.Qt.LeftButton
and obj.whatsThis() and
obj.testAttribute(QtCore.Qt.WA_CustomWhatsThis)):
self.whatsThis = SelectableWhatsThis(obj, event.globalPos())
QtWidgets.QApplication.restoreOverrideCursor()
return True
elif event.type() in (event.MouseButtonRelease, event.MouseButtonDblClick):
if self.whatsThis:
QtWidgets.QWhatsThis.leaveWhatsThisMode()
return True
elif event.type() == event.LeaveWhatsThisMode:
QtWidgets.QApplication.instance().removeEventFilter(self)
self.deleteLater()
return super().eventFilter(obj, event)
def __del__(self):
if self.active:
self.__class__.installed = False
class MainWindow(QtWidgets.QMainWindow):
# ...
def event(self, event):
if event.type() == event.EnterWhatsThisMode:
WhatsThisHelper(self)
return super().event(event)
Note that you need to override the event of all widgets that are going to be top level widgets (all QMainWindows, QDialogs, etc) and need to support this.

How can I know when the Enter key was pressed on QTextEdit

I'm writing Chat gui for client on Python using PyQt5.
I have a QTextEdit, which the client can write messages in it.
I wan't to know when the 'Enter' key is being pressed while the focus is on the QTextEdit.
I tried using installEventFilter function but it detects keys being pressed on all of the other widgets but the QTextEdit one.
What can I do to fix that?
def initUI(self):
# ...
self.text_box = QtWidgets.QTextEdit(self)
self.installEventFilter(self)
# ...
def keyPressEvent(self, qKeyEvent):
print(qKeyEvent.key())
if qKeyEvent.key() == Qt.Key_Return:
if self.text_box.hasFocus():
print('Enter pressed')
When you override keyPressEvent you are listening to the events of the window, instead install an eventFilter to the QTextEdit, not to the window as you have done in your code, and check if the object passed as an argument is the QTextEdit:
def initUI(self):
# ...
self.text_box = QtWidgets.QTextEdit(self)
self.text_box.installEventFilter(self)
# ...
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyPress and obj is self.text_box:
if event.key() == QtCore.Qt.Key_Return and self.text_box.hasFocus():
print('Enter pressed')
return super().eventFilter(obj, event)
The answer from #eyllanesc is very good if you are determined to use QTextEdit.
If you can get away with QLineEdit and its limitations, you can use the returnPressed() signal. The biggest drawback for QLineEdit is you are limited to one line of text. And there is no word wrap. But the advantage is you don't have to mess with eventFilters or think too hard about how keyPress signals fall through all of the widgets in your app.
Here is a minimal example that copies from one QLineEdit to another:
import sys
from PyQt5.QtWidgets import *
class PrintWindow(QMainWindow):
def __init__(self):
super().__init__()
self.left=50
self.top=50
self.width=300
self.height=300
self.initUI()
def initUI(self):
self.setGeometry(self.left,self.top,self.width,self.height)
self.line_edit1 = QLineEdit(self)
self.line_edit1.move(50, 50)
self.line_edit1.returnPressed.connect(self.on_line_edit1_returnPressed)
self.line_edit2 = QLineEdit(self)
self.line_edit2.move(50, 100)
self.show()
def on_line_edit1_returnPressed(self):
self.line_edit2.setText(self.line_edit1.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
window = PrintWindow()
sys.exit(app.exec_())
In this example, I have manually connected to the signal in line 22 (self.line_edit1.returnPressed.connect). If you are using a ui file, this connection can be left out and your program will automatically call the on__returnPressed method.
When you override keyPressEvent you are listening to the events of the window, instead install an eventFilter to the QTextEdit, not to the window as you have done in your code, and check if the object passed as an argument is the QTextEdit:
def initUI(self):
# ...
self.text_box = QtWidgets.QTextEdit(self)
self.text_box.installEventFilter(self)
# ...
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyPress and obj is self.text_box:
if event.key() == QtCore.Qt.Key_Return and self.text_box.hasFocus():
print('Enter pressed')
return True
return False
This is building upon the answer of #eyllanesc and the problem #Daniel Segal faced. Adding the correct return values as such to the eventFilter solves the problem.

Update a QLineEdit on a WheelEvent when scroll bar is already set

I'm trying to update a QLineEdit when I do a wheel move on the mouse and if I press a number on the keyboard at the same time. Unfortunatly, I don't see a mouse wheel event for QLineEdit widget so I don't understand how I can set a signal to each QLineEdit. The other issue I have is as the QLineEdit are already in a scroll bar environment, I cannot detect all wheel event because the scroll is done first.
For instance with this code:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.centralTabs= QTabWidget()
self.setCentralWidget(self.centralTabs)
self.setFixedWidth(200)
self.setFixedHeight(200)
#tab Model selection
self.tab_ModelSelect = QWidget()
self.centralTabs.addTab(self.tab_ModelSelect,"Label")
self.groupscrolllayouttest = QHBoxLayout() ####
self.groupscrollbartest = QGroupBox() ####
self.mainHBOX_param_scene = QVBoxLayout()
for i in range(10):
LineEdit = QLineEdit(str(i))
LineEdit.setFixedWidth(200)
self.mainHBOX_param_scene.addWidget(LineEdit)
self.installEventFilter(self)
scroll = QScrollArea()
widget = QWidget(self)
widget.setLayout(QVBoxLayout())
widget.layout().addWidget(self.groupscrollbartest)
scroll.setWidget(widget)
scroll.setWidgetResizable(True)
self.groupscrollbartest.setLayout(self.mainHBOX_param_scene)
self.groupscrolllayouttest.addWidget(scroll)
self.tab_ModelSelect.setLayout(self.groupscrolllayouttest)
def eventFilter(self, widget, event):
if (event.type() == QEvent.Wheel) :
# get which key is pressed
# if the key is a number, put the number in 'num' variable
# get on which QLineEdit the wheel was make
# set the text of that QLineEdit to previous value +- num
event.ignore()
return QWidget.eventFilter(self, widget, event)
def main():
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
# ex.showMaximized()
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()
I tried to something with wheelevent but as mention, I don't enter in this function because the scroll bar is activated first. I tried to test if the wheel event happend on a QLineEdit but I even struggle to do that...
What I'm seeking to do is when I do a wheelevent with the mouse on a QlineEdit with the '5' key pressed, I want increase or decrease the QLineEdit text by 5 according to the direction of the mouse wheel.
I red some post with eventfilter (as How to get Click Event of QLineEdit in Qt?) but I don't understand how does this work.
In my eventFilter function, I need to do several step:
# get which key is pressed
# if the key is a number, put the number in 'num' variable
# get on which QLineEdit the wheel was make
# set the text of that QLineEdit to previous value +- num
but I don't know how to make them. In particular getting the pressed key and knowing on which QlineEdit the wheel was made.
If you wish that all QLineEdit have that behavior then it is appropriate that you create your own class and overwrite the necessary events, to avoid that when you move the scroll when the pointer is inside the QLineEdit and pressing an established key, we accept the event so that it does not propage.
Another recommendation is not to use the 5 key since this is a text that QLineEdit can handle causing problems, for this you can use the SHIFT key:
class LineEdit(QLineEdit):
KEY = Qt.Key_Shift
def __init__(self, *args, **kwargs):
QLineEdit.__init__(self, *args, **kwargs)
self.isKeyPressed = False
def keyPressEvent(self, event):
if event.key() == LineEdit.KEY:
self.isKeyPressed = True
QLineEdit.keyPressEvent(self, event)
def keyReleaseEvent(self, event):
if event.key() == LineEdit.KEY:
self.isKeyPressed = False
QLineEdit.keyReleaseEvent(self, event)
def wheelEvent(self, event):
if self.isKeyPressed:
delta = 1 if event.angleDelta().y() > 0 else -1
fn = self.font()
fn.setPointSize(fn.pointSize() + delta)
self.setFont(fn)
event.accept()
The complete example:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class LineEdit(QLineEdit):
KEY = Qt.Key_Shift
def __init__(self, *args, **kwargs):
QLineEdit.__init__(self, *args, **kwargs)
self.isKeyPressed = False
def keyPressEvent(self, event):
if event.key() == LineEdit.KEY:
self.isKeyPressed = True
QLineEdit.keyPressEvent(self, event)
def keyReleaseEvent(self, event):
if event.key() == LineEdit.KEY:
self.isKeyPressed = False
QLineEdit.keyReleaseEvent(self, event)
def wheelEvent(self, event):
if self.isKeyPressed:
delta = 1 if event.angleDelta().y() > 0 else -1
fn = self.font()
fn.setPointSize(fn.pointSize() + delta)
self.setFont(fn)
event.accept()
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.centralTabs= QTabWidget()
self.setCentralWidget(self.centralTabs)
self.setFixedWidth(200)
self.setFixedHeight(200)
#tab Model selection
self.tab_ModelSelect = QWidget()
self.centralTabs.addTab(self.tab_ModelSelect,"Label")
self.groupscrolllayouttest = QHBoxLayout() ####
self.groupscrollbartest = QGroupBox() ####
self.mainHBOX_param_scene = QVBoxLayout()
for i in range(10):
le = LineEdit(str(i))
le.setFixedWidth(200)
self.mainHBOX_param_scene.addWidget(le)
self.installEventFilter(self)
scroll = QScrollArea()
widget = QWidget(self)
widget.setLayout(QVBoxLayout())
widget.layout().addWidget(self.groupscrollbartest)
scroll.setWidget(widget)
scroll.setWidgetResizable(True)
self.groupscrollbartest.setLayout(self.mainHBOX_param_scene)
self.groupscrolllayouttest.addWidget(scroll)
self.tab_ModelSelect.setLayout(self.groupscrolllayouttest)
def main():
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
# ex.showMaximized()
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()

Implementing keyPressEvent in QWidget

I have a QDialog window that has a continue button. The continue button is the default button because whenever I press the enter key, the continue button is pressed. I discovered something strange: when I press the enter key three times, the continue button presses three times. However, when I press it a fourth time, the whole window closes. I have a cancel button right below the continue button that closes the window, but I don't make the cancel button the default button or anything.
I wanted to override the keyPressEvent so that whenever I'm in the window, the enter button will always be connected to the continue button.
This is what I have right now:
class ManualBalanceUI(QtGui.QWidget):
keyPressed = QtCore.pyqtSignal()
def __init__(self, cls):
super(QtGui.QWidget, self).__init__()
self.window = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint)
self.ui = uic.loadUi('ManualBalanceUI.ui', self.window)
self.keyPressed.connect(self.on_key)
def keyPressEvent(self, event):
super(ManualBalanceUI, self).keyPressEvent(event)
self.keyPressed.emit(event)
def on_key(self, event):
if event.key() == QtCore.Qt.Key_Enter and self.ui.continueButton.isEnabled():
self.proceed() # this is called whenever the continue button is pressed
elif event.key() == QtCore.Qt.Key_Q:
self.window.close() # a test I implemented to see if pressing 'Q' would close the window
def proceed(self):
...
...
However, this doesn't seem to be doing anything right now. Pressing 'Q' doesn't close the window, and I can't really tell if the 'enter' key is working or not.
I looked at this question beforehand: PyQt Connect to KeyPressEvent
I also reviewed all the documentation on SourceForge. Any help would be greatly appreciated!
You can do two ways and one is simply re implement keyPressevent with out any fancy work. Like this
from PyQt4 import QtCore, QtGui
import sys
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.setGeometry(300, 300, 250, 150)
self.show()
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Q:
print "Killing"
self.deleteLater()
elif event.key() == QtCore.Qt.Key_Enter:
self.proceed()
event.accept()
def proceed(self):
print "Call Enter Key"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Or as you tried with signals, in your case you where missing to implement this signal properly, here is updated version.
class Example(QtGui.QWidget):
keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
def __init__(self):
super(Example, self).__init__()
self.setGeometry(300, 300, 250, 150)
self.show()
self.keyPressed.connect(self.on_key)
def keyPressEvent(self, event):
super(Example, self).keyPressEvent(event)
self.keyPressed.emit(event)
def on_key(self, event):
if event.key() == QtCore.Qt.Key_Enter and self.ui.continueButton.isEnabled():
self.proceed() # this is called whenever the continue button is pressed
elif event.key() == QtCore.Qt.Key_Q:
print "Killing"
self.deleteLater() # a test I implemented to see if pressing 'Q' would close the window
def proceed(self):
print "Call Enter Key"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
If you're looking at this in 2019, and If Achayan's method does not work for you then check a couple things :
1) Is the keyPressEvent overridden in a child of the main window or main widget? The child's function will override the methods on the parent (at least when using a QMainWindow with setCentralWidget). If this is the case, then the signal might not be emitted like you expect
2) Do you have a widget that handles key inputs differently than QWidget? For example, if the focus is in a QTextEdit object, then key inputs will not be sent to keyPressEvent. Shift focus to another widget
For example, observe the output of the following :
class myDialog(QtWidgets.QDialog):
keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
def __init__(self, parent=None):
super(myDialog, self).__init__(parent)
self.keyPressed.connect(self.on_key)
leftGroupBox = QtWidgets.QGroupBox('A Group Label')
text = QtWidgets.QTextEdit('Enter some text')
layout = QtWidgets.QVBoxLayout()
layout.addWidget(text)
leftGroupBox.setLayout(layout)
rightGroupBox = QtWidgets.QGroupBox('Label Options')
label1 = QtWidgets.QCheckBox('ahu')
layout = QtWidgets.QVBoxLayout()
layout.addWidget(label1)
rightGroupBox.setLayout(layout)
# Create the main layout
mainLayout = QtWidgets.QGridLayout()
mainLayout.addWidget(leftGroupBox)
mainLayout.addWidget(rightGroupBox)
self.setLayout(mainLayout)
def keyPressEvent(self, event):
# keyPressEvent defined in child
print('pressed from myDialog: ', event.key())
# self.keyPressed.emit(event) # Emit is hidden in child
def on_key(self, event):
print('event received # myDialog')
if event.key() == QtCore.Qt.Key_0:
print(0)
class MainWindow(QtWidgets.QMainWindow):
keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
def __init__(self):
super(MainWindow, self).__init__()
self.keyPressed.connect(self.on_key)
self.setCentralWidget(myDialog())
self.show()
def keyPressEvent(self, event):
super(MainWindow, self).keyPressEvent(event)
print('pressed from MainWindow: ', event.key())
self.keyPressed.emit(event)
def on_key(self, event):
print('event received # MainWindow')
if event.key() == QtCore.Qt.Key_0:
print(0)
if __name__ == '__main__':
ex = MainWindow()
Output # console : (no event is received #myDialog OR MainWindow)
pressed from myDialog: 48
For Achayan's answer, I succeeded with the code.
It may be the enter key and the return key.
Try Key_Enter and Key_Return. They are different on my keyboard.
QtCore.QObject.connect(self.ui.search_box, QtCore.SIGNAL("textChanged()"), self.fucn1)
Whenever text is changed in search_box function fucn1 is called.
Works for pyqt4

Detecting Key Sequences

I am using pyqt's Qshortcut in trying to detect a key combination to trigger some action i.e when
the user types -> into a QtextEdit widget, I would like to print "changing mode".
I have seen other key sequence examples that involve CTRL+E or some other CTRL or shift key
combination,
self.shcut1 = QtGui.QShortcut(self)
self.shcut1.setKey("CTRL+E")
self.connect(self.shcut1, QtCore.SIGNAL("activated()"), self.close)
But I really want to trap ->(hyphen followed by a greater than sign). Any suggestions on how to do this
QShortCut only accepts combinations of QtCore.Qt::KeyboardModifiers. Try using an event filter:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui, QtCore
class MyWindow(QtGui.QTextEdit):
modeChanged = QtCore.pyqtSignal(bool)
_seenMinus = False
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.installEventFilter(self)
self.modeChanged.connect(self.on_modeChanged)
def on_modeChanged(self):
print "Changing Mode."
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyPress:
if event.key() == QtCore.Qt.Key_Minus:
self._seenMinus = True
elif event.key() == QtCore.Qt.Key_Greater \
and event.modifiers() == QtCore.Qt.ShiftModifier \
and self._seenMinus:
self.modeChanged.emit(True)
self.setStyleSheet("""
background-color: lightgray;
""")
elif event.modifiers() != QtCore.Qt.ShiftModifier:
if self._seenMinus == True:
self.modeChanged.emit(False)
self._seenMinus = False
self.setStyleSheet("")
return super(MyWindow, self).eventFilter(obj, event)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())
Just catch the signal QTextEdit::textChanged(), and every the user makes a change, scan the text for '->'. Granter the brute force approach of scanning the entire text block every time isn't pretty; another option is scanning only the last two characters of the text. However this misses the case where the user creates '->' by deleting text in between a '-' and a '>' character. If you're not worried about that case, then just go with the last two. QTextEdit::cursorPositionChanged might allow you to test precisely at the insertion/deletion point.

Categories