Create a simple text editor with autocomplete using…
- User
Create a simple text editor with autocomplete using QCompleter.CompletionMode.InlineCompletion in python. The suggested completion should just be a random word for now.
Assistant
Okay, here's a simple Python script using PyQt5 (you can adapt it slightly for PyQt6 if needed) that creates a basic text editor featuring inline autocompletion with random words.
import sys import random from PyQt5.QtWidgets import (QApplication, QWidget, QTextEdit, QVBoxLayout, QCompleter) from PyQt5.QtCore import Qt, QStringListModel # A list of words for autocompletion suggestions # In a real application, this could come from a file, database, etc. WORD_LIST = [ "apple", "apricot", "avocado", "banana", "blackberry", "blueberry", "cantaloupe", "cherry", "coconut", "cranberry", "date", "dragonfruit", "durian", "elderberry", "fig", "grape", "grapefruit", "guava", "honeydew", "kiwi", "lemon", "lime", "lychee", "mango", "melon", "nectarine", "orange", "papaya", "peach", "pear", "persimmon", "pineapple", "plum", "pomegranate", "raspberry", "strawberry", "tangerine", "watermelon" ] class TextEditorWithCompletion(QTextEdit): def __init__(self, parent=None): super().__init__(parent) self._completer = None self.setup_completer(WORD_LIST) def setup_completer(self, word_list): # Create a completer completer = QCompleter(self) # Set the completion mode to InlineCompletion # This makes the suggestion appear directly in the text edit completer.setCompletionMode(QCompleter.InlineCompletion) # Set case sensitivity (usually insensitive is better for users) completer.setCaseSensitivity(Qt.CaseInsensitive) # Set the filter mode (e.g., starts with, contains) completer.setFilterMode(Qt.MatchStartsWith) # Or Qt.MatchContains # Create a model with our word list model = QStringListModel(word_list, self) completer.setModel(model) # Assign the completer self.setCompleter(completer) def setCompleter(self, completer): if self._completer: self._completer.activated.disconnect() self._completer = completer if not self._completer: return self._completer.setWidget(self) # The activated signal is fired when a completion is selected self._completer.activated.connect(self.insertCompletion) def completer(self): return self._completer def insertCompletion(self, completion): if self._completer.widget() is not self: return tc = self.textCursor() # Get length of the prefix being completed extra = len(completion) - len(self._completer.completionPrefix()) # Insert the remaining part of the completion tc.movePosition(tc.Left) tc.movePosition(tc.EndOfWord) tc.insertText(completion[-extra:]) self.setTextCursor(tc) def textUnderCursor(self): tc = self.textCursor() # Select characters backward until a non-word character is found tc.select(tc.WordUnderCursor) return tc.selectedText() def keyPressEvent(self, event): # Handle key presses related to completion if self._completer and self._completer.popup().isVisible(): # These keys could potentially accept the completion if event.key() in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Escape, Qt.Key_Tab, Qt.Key_Backtab): event.ignore() return # Let the completer handle it # Check if the pressed key should trigger completion logic # We want standard alphanumeric keys, but not modifiers alone is_shortcut = (event.modifiers() & Qt.ControlModifier) and event.key() == Qt.Key_E if not self._completer or is_shortcut: # Basic check (e.g., Ctrl+E maybe?) super().keyPressEvent(event) # Default handling # --- Standard key press handling --- # Let the base class handle the key press first (e.g., insert the character) super().keyPressEvent(event) # Update the completion prefix based on the text before the cursor ctrl_or_shift = event.modifiers() & (Qt.ControlModifier | Qt.ShiftModifier) if not self._completer or ctrl_or_shift: # Don't try to complete if Ctrl or Shift is held (e.g., for selection) return # Determine the word being typed current_word = self.textUnderCursor() # If the current word is different or empty, update the completer if current_word != self._completer.completionPrefix(): self._completer.setCompletionPrefix(current_word) # For inline completion, setting the prefix often triggers the update # But we might need to explicitly show it if it's not appearing # self._completer.popup().setCurrentIndex(self._completer.completionModel().index(0, 0)) # For InlineCompletion, the suggestion appears automatically if a match is found # No need to explicitly call completer.complete() or position a popup rect # You *might* need this if inline completion isn't triggering reliably # if self._completer.completionCount() > 0 and current_word: # cr = self.cursorRect() # self._completer.complete(cr) class MainWindow(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Simple Text Editor with Inline Completion") self.setGeometry(100, 100, 500, 400) # x, y, width, height layout = QVBoxLayout(self) self.editor = TextEditorWithCompletion(self) self.editor.setPlaceholderText("Start typing a fruit name (e.g., 'ap')...") layout.addWidget(self.editor) self.setLayout(layout) if __name__ == '__main__': app = QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit(app.exec_())Explanation:
WORD_LIST: A simple Python list containing the words that will be used for suggestions.TextEditorWithCompletion(QTextEdit): We subclassQTextEditto add our custom completion logic.__init__: Calls the parent constructor and sets up the completer usingsetup_completer.setup_completer:- Creates a
QCompleterinstance. - Sets the
completionModetoQCompleter.InlineCompletion. This is the crucial part for making suggestions appear within the text edit widget as you type. - Sets
caseSensitivity(usuallyQt.CaseInsensitiveis best). - Sets
filterMode(e.g.,Qt.MatchStartsWithfinds words starting with your prefix). - Creates a
QStringListModelusing ourword_list. This model provides the data to the completer. - Assigns the model to the completer.
- Calls
setCompleterto link the completer to this text edit widget.
- Creates a
setCompleter: A standard method often used withQCompleter. It disconnects any old completer, stores the new one, sets its widget (self), and connects theactivatedsignal to ourinsertCompletionslot.insertCompletion(completion): This method is called when a completion suggestion is activated (typically by the completer itself in inline mode when a unique match is found or potentially by user action like Tab/Enter if configured differently, although inline mode handles this implicitly). It inserts the rest of the suggested word into the text edit.textUnderCursor(): A helper method to determine the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.