我正在尝试为QCombobox
和QCompleter
创建一个子类,以实现以下目的:
我想制作一个可编辑的组合框,当用户开始键入内容时,该组合框会弹出完成列表。
Ex:完成列表-QStringList<<"manual"<<"anual"
当我键入'anu'
时,我希望"manual"
和"anual"
都出现在完成下拉列表中,因为它们都包含"anu"
。
但是相反,我只得到**anu**al
,其中al
作为内联完成,因此在完成列表中,我只有"anual"
。
当我使用退格键删除内联建议时,我将按预期获得完整列表。
为什么会显示默认的内联完成?
linecompleter.h
#ifndef LINECOMPLETER_H
#define LINECOMPLETER_H
#include <QtGui>
#include <QtWidgets>
class QKeyEvent;
class LineCompleter : public QCompleter
{
Q_OBJECT
public:
inline LineCompleter(const QStringList& words, QObject * parent) :
QCompleter(parent), m_list(words), m_model()
{
setModel(&m_model);
}
inline void update(QString word)
{
// Do any filtering you like.
// Here we just include all items that contain word.
QStringList filtered = m_list.filter(word, caseSensitivity());
m_model.setStringList(filtered);
m_word = word;
complete();
}
inline QString word()
{
return m_word;
}
private:
QStringList m_list;
QStringListModel m_model;
QString m_word;
};
class PageLineEdit : public QComboBox
{
Q_OBJECT
public:
PageLineEdit(QWidget *parent = 0);
~PageLineEdit();
void setCompleter(LineCompleter *c);
LineCompleter *completer() const;
protected:
void keyPressEvent(QKeyEvent *e);
private slots:
void insertCompletion(const QString &completion);
private:
LineCompleter *c;
};
#endif // LINECOMPLETER_H
linecompleter.cpp
#include "linecompleter.h"
PageLineEdit::PageLineEdit(QWidget *parent)
: QComboBox(parent), c(0)
{
}
PageLineEdit::~PageLineEdit()
{
}
void PageLineEdit::setCompleter(LineCompleter *completer)
{
if (c)
QObject::disconnect(c, 0, this, 0);
c = completer;
if (!c)
return;
c->setWidget(this);
c->setCompletionMode(QCompleter::PopupCompletion);
c->setCaseSensitivity(Qt::CaseInsensitive);
QObject::connect(c, SIGNAL(activated(QString)),
this, SLOT(insertCompletion(QString)));
}
LineCompleter *PageLineEdit::completer() const
{
return c;
}
void PageLineEdit::insertCompletion(const QString& completion)
{
lineEdit()->setText(completion);
lineEdit()->selectAll();
}
void PageLineEdit::keyPressEvent(QKeyEvent *e)
{
if (c && c->popup()->isVisible())
{
// The following keys are forwarded by the completer to the widget
switch (e->key())
{
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Escape:
case Qt::Key_Tab:
case Qt::Key_Backtab:
e->ignore();
return; // Let the completer do default behavior
default:
break;
}
}
bool isShortcut = (e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E;
if (!isShortcut)
QComboBox::keyPressEvent(e); // Don't send the shortcut (CTRL-E) to the text edit.
if (!c)
return;
bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
if (!isShortcut && !ctrlOrShift && e->modifiers() != Qt::NoModifier)
{
c->popup()->hide();
return;
}
c->update(lineEdit()->text());
c->popup()->setCurrentIndex(c->completionModel()->index(0, 0));
}
来实现
我正在使用没有setFilterMode()
的{{1}}的Qt 4.8。
如何正确地将QCompleter
子类化以实现此必需功能?