如何在QTableWidget中弹出QCompleter进入单元格编辑

时间:2018-03-23 13:42:14

标签: c++ qt qcompleter qstyleditemdelegate

我有QTableWidget自定义QStyledItemDelegate,当进入单元格编辑时,我想弹出一个完成者,但它不会出现。

委托的设置:

tableWidget.setItemDelegate(new DelegateLineEdit());

我的自定义课程:

class DelegateLineEdit : public QStyledItemDelegate
{
public:
    DelegateLineEdit() {
        signs << "<" << "<=" << ">" << ">=" << "=";
    }
    ~DelegateLineEdit(){ }
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
        QLineEdit *line_edit = new QLineEdit(parent);
        line_edit->setStyle(parent->style());
        line_edit->setFocusPolicy(Qt::StrongFocus);
        QCompleter *completer = new QCompleter(signs, line_edit);
        completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
        line_edit->setCompleter(completer);
        return line_edit;
    }
    void setEditorData(QWidget *editor, const QModelIndex &index) const {
        QStyledItemDelegate::setEditorData(editor, index);
        QLineEdit *line_edit = dynamic_cast<QLineEdit*>(editor);
        if (line_edit){
            line_edit->completer()->complete();
        }
    }

private:
    QStringList signs;

};

当我通过双击进入单元格编辑时,没有任何反应,但是如果我对该行进行评论 line_edit->completer()->complete(),我可以编辑单元格,但不显示完成情况。有人有想法吗?

2 个答案:

答案 0 :(得分:1)

我会尝试使用QLineEdit子类作为编辑器,其中重写focusInEvent以显示弹出窗口:

class LineEdit : public QLineEdit
{
public:
  explicit LineEdit(QWidget*parent) : QLineEdit(parent){}
protected:
  void focusInEvent(QFocusEvent * e)
  {
    QLineEdit::focusInEvent(e);
    completer()->complete();
  }
};

代表成为:

class DelegateLineEdit : public QStyledItemDelegate
{
public:
    DelegateLineEdit() {
        signs << "<" << "<=" << ">" << ">=" << "=";
    }
    ~DelegateLineEdit(){ }
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {

//use the subclass instead of QLineEdit:
        LineEdit *line_edit = new LineEdit(parent);

        line_edit->setStyle(parent->style());
        line_edit->setFocusPolicy(Qt::StrongFocus);
        QCompleter *completer = new QCompleter(signs, line_edit);
        completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
        line_edit->setCompleter(completer);
        return line_edit;
    }

private:
    QStringList signs;

};

答案 1 :(得分:0)

我觉得像completer->popup()->show();之类的东西应该做你想要的或试着像

那样打电话
QCompleter::setCompletionPrefix(index.data(Qt::EditRole).tostring());

QCompleter::complete();