Avoiding multiple text selections
-
Hi!
I'm working on a PyQt5-based application which contains multiple QPlainTextEdits and QTextBrowsers. I noticed a behavior that I find a bit unintuitive: those widgets can each keep their own text selections independently. For example:
from PyQt5.QtWidgets import ( QApplication, QMainWindow, QWidget, QVBoxLayout, QPlainTextEdit, QTextBrowser, ) class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() layout = QVBoxLayout() widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) editor = QPlainTextEdit(widget) layout.addWidget(editor) browser = QTextBrowser(widget) browser.append("ABCDEF") layout.addWidget(browser) app = QApplication([]) window = MainWindow() window.show() app.exec()
If you enter some text in the QPlainTextEdit and select it, then select something in the QTextBrowser, you get two simultaneous selections.
I found that I can avoid this with a mixin class that does
def focusOutEvent(self, ev): cursor = self.textCursor() cursor.clearSelection() self.setTextCursor(cursor)
My question: is there a simpler way to do this, rather than changing each of the widget classes? Can I just tell Qt "clear the text selection whenever a widget is unfocused"?
-
And of course, 5 minutes after asking, I found that I can connect my
QApplication
'sfocusChanged
signal to something likedef clear_selection(old, new): if isinstance(old, (QPlainTextEdit, QTextEdit)): cursor = old.textCursor() cursor.clearSelection() old.setTextCursor(cursor)
I still wonder if there is a better way, though.