Using A Qcompleter In A Qtableview With Qt And Python
I'm reading up on how to make my QAbstractTableModel editable, and it looks pretty straightforward. But how do I set up an editable cell to use a QCompleter? I take it somehow I ha
Solution 1:
Create a subclass of QStyledItemDelegate
All you need to do is reimplement the setEditorData
function, check that the editor widget is a QLineEdit
and then set the completer.
Please, excuse that I don't know Python but this is how it would be done in C++. Hopefully, translating to Python will be easy.
classMyDelegate : public QStyledItemDelegate{
public:
voidsetEditorData(QWidget *editor, QModelIndex const &index){
// call the superclass' function so that the editor widget gets the correct data
QStyledItemDelegate::setEditorData(editor, index);
// Check that the editor passed in is a QLineEdit.
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(editor);
if (lineEdit != nullptr){
// add whatever completer is needed, making sure that the editor is the parent QObject so it gets deleted along with the editor
lineEdit.setComplete(newMyCompleter(editor));
}
}
};
Solution 2:
Per RobbieE's suggestion, I subclassed QStyledItemDelegate. But the correct place to apply the completer is when the editor is created, not setEditorData.
classCompleterDelegate(QtGui.QStyledItemDelegate):
def__init__(self, parent=None, completerSetupFunction=None):
super(CompleterDelegate, self).__init__(parent)
self._completerSetupFunction = completerSetupFunction
defcreateEditor(self, parent, option, index):
editor = QtGui.QLineEdit(parent)
self._completerSetupFunction(editor, index)
return editor
and then I use a completerSetupFunction that basically looks like this:
def_completerSetupFunction(editor, index):
print"completer setup: editor=%s, index=%s" % (editor, index)
completer = QtGui.QCompleter(base_items, editor)
completer.setCompletionColumn(0)
completer.setCompletionRole(QtCore.Qt.EditRole)
completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
try:
editor.setCompleter(completer)
except:
pass
Here's a complete example as a github gist.
Post a Comment for "Using A Qcompleter In A Qtableview With Qt And Python"