Skip to content

Instantly share code, notes, and snippets.

@jimbob88
Created September 3, 2022 16:56
Show Gist options
  • Save jimbob88/958d009000ace3459de2d55a707e9219 to your computer and use it in GitHub Desktop.
Save jimbob88/958d009000ace3459de2d55a707e9219 to your computer and use it in GitHub Desktop.
Continuous Autocomplete in a textbox Qt
"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
"""
import keyword
import sys
from typing import List
from PySide6.QtCore import QStringListModel, QSize
from PySide6.QtGui import QTextCursor, QKeyEvent, Qt
from PySide6.QtWidgets import QTextEdit, QWidget, QCompleter, QMainWindow, QApplication
class CustomTextEdit(QTextEdit):
"""An inline QCompleter for a QTextEdit
Source: https://web.archive.org/web/20130508195128/http://qt-project.org/forums/viewthread/5376
"""
def __init__(self, parent: QWidget, match: List[str]):
super().__init__(parent)
self.m_completer = QCompleter(self)
self.m_completer.setWidget(self)
self.model = QStringListModel(match, self.m_completer)
self.m_completer.setModel(self.model)
self.m_completer.setCompletionMode(QCompleter.PopupCompletion)
self.m_completer.activated.connect(self.insert_completion)
def insert_completion(self, completion: str):
cursor = self.textCursor()
extra = len(completion) - len(self.m_completer.completionPrefix())
cursor.movePosition(QTextCursor.Left)
cursor.movePosition(QTextCursor.EndOfWord)
if extra:
cursor.insertText(completion[-extra:])
self.setTextCursor(cursor)
def text_under_cursor(self) -> str:
cursor = self.textCursor()
cursor.select(QTextCursor.WordUnderCursor)
return cursor.selectedText()
def keyPressEvent(self, event: QKeyEvent):
if self.m_completer.popup().isVisible():
if event.key() in [Qt.Key_Enter, Qt.Key_Return, Qt.Key_Escape, Qt.Key_Tab]:
event.ignore()
return
super().keyPressEvent(event)
completion_prefix = self.text_under_cursor()
if completion_prefix != self.m_completer.completionPrefix():
self.m_completer.setCompletionPrefix(completion_prefix)
self.m_completer.popup().setCurrentIndex(
self.m_completer.completionModel().index(0, 0)
)
if event.text() and len(completion_prefix) > 2:
self.m_completer.complete()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
line_edit = CustomTextEdit(self, keyword.kwlist)
self.setFixedSize(QSize(400, 300))
self.setCentralWidget(line_edit)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment