Skip to content

Instantly share code, notes, and snippets.

@estan
Last active February 18, 2016 10:27
Show Gist options
  • Save estan/6e2df5643567e5a1bc31 to your computer and use it in GitHub Desktop.
Save estan/6e2df5643567e5a1bc31 to your computer and use it in GitHub Desktop.
Custom delegate with completions from file
from PyQt5.QtCore import QFile, QIODevice, Qt
from PyQt5.QtWidgets import QStyledItemDelegate, QComboBox
# noinspection PyUnresolvedReferences
from orexplore.gui.ui import rock_types_rc # noqa
class RockTypeDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(RockTypeDelegate, self).__init__(parent)
self._availableTypes = []
# Read available rock types from resource file.
name = ':/rock_types/all.txt'
file = QFile(name)
if not file.open(QIODevice.ReadOnly):
raise IOError('{}: {}'.format(name, file.errorString()))
while not file.atEnd():
type = unicode(file.readLine().trimmed(), 'utf-8')
self._availableTypes.append(type)
def setEditorData(self, editor, index):
editor.setCurrentText(index.data(Qt.EditRole))
editor.lineEdit().selectAll()
def createEditor(self, parent, option, index):
comboBox = QComboBox(parent)
comboBox.setEditable(True)
for type in self._availableTypes:
comboBox.addItem(type)
return comboBox
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment