1

我有一个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(),我可以编辑单元格但不显示完成。有人有想法吗?

4

2 回答 2

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;

};
于 2018-03-23T18:43:15.007 回答
0

我认为类似的东西completer->popup()->show();应该做你想做的事或试着打电话

QCompleter::setCompletionPrefix(index.data(Qt::EditRole).tostring());

QCompleter::complete();
于 2018-03-23T15:11:00.203 回答