1

我正在阅读如何使我的 QAbstractTableModel 可编辑,它看​​起来非常简单。

但是如何设置一个可编辑的单元格来使用 QCompleter?我以某种方式必须告诉 QTableView 使用 QLineEdit 小部件?我怎样才能做到这一点?


编辑:嗯,我猜它与QTableView.setItemDelegateForColumn()有一些关系,但我对代表或如何使用它们一无所知。


编辑:我尝试了 RobbieE 的解决方案,得到了一些可行的方法,但是当我按下 Enter 时,它使弹出组合框的几何形状错误并导致 Python 崩溃。

class CompleterDelegate(QtGui.QStyledItemDelegate):
    def __init__(self, parent=None, completerSetupFunction=None):
        super(CompleterDelegate, self).__init__(parent)
        self._completerSetupFunction = completerSetupFunction
    def createEditor(self, parent, option, index):
        return QtGui.QLineEdit(parent)
    def setEditorData(self, editor, index):
        super(CompleterDelegate, self).setEditorData(editor, index)
        self._completerSetupFunction(editor, index)

我的 _completerSetupFunction 看起来像这样:

def setupFunc(editor, index):
    completer = MyCompleter(editor)
    completer.setCompletionColumn(0)
    completer.setCompletionRole(QtCore.Qt.DisplayRole)
    completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)    
    editor.setCompleter(completer)
    completer.setModel(myAbstractItemModel)
4

2 回答 2

3

创建一个子类QStyledItemDelegate

您需要做的就是重新实现该setEditorData功能,检查编辑器小部件是否为 a QLineEdit,然后设置完成者。

请原谅我不了解 Python,但这是在 C++ 中完成的。希望翻译成 Python 会很容易。

class MyDelegate : public QStyledItemDelegate{
     public:
         void setEditorData(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(new MyCompleter(editor));
             }
         }
}; 
于 2014-07-25T07:05:41.890 回答
2

根据 RobbieE 的建议,我将QStyledItemDelegate子类化。但是应用完成者的正确位置是在创建编辑器时,而不是 setEditorData。

class CompleterDelegate(QtGui.QStyledItemDelegate):
    def __init__(self, parent=None, completerSetupFunction=None):
        super(CompleterDelegate, self).__init__(parent)
        self._completerSetupFunction = completerSetupFunction
    def createEditor(self, parent, option, index):
        editor = QtGui.QLineEdit(parent)
        self._completerSetupFunction(editor, index)
        return editor

然后我使用一个 completerSetupFunction ,它基本上看起来像这样:

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

这是一个完整的 github gist 示例

于 2014-08-25T21:33:25.723 回答