Подкласс ваш QLineEdit
с 2 таможенными QCompleter
ExtendedLineEdit.h
class ExtendedLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit ExtendedLineEdit(QWidget *parent = nullptr);
void setWordCompleter(QCompleter* c);
void setNumberCompleter(QCompleter* c);
protected:
void keyPressEvent(QKeyEvent *e);
private slots:
void insertCompletionWord(const QString& txtComp);
void insertCompletionNumber(const QString& txtComp);
private:
QCompleter* m_completerWord;
QCompleter* m_completerNumber;
void showCustomCompleter(QCompleter* completer);
};
ExtendedLineEdit.cpp
ExtendedLineEdit::ExtendedLineEdit(QWidget *parent) :
QLineEdit(parent)
{
}
void ExtendedLineEdit::setWordCompleter(QCompleter *c)
{
m_completerWord = c;
m_completerWord->setWidget(this);
connect(m_completerWord, SIGNAL(activated(QString)),
this, SLOT(insertCompletionWord(QString)));
}
void ExtendedLineEdit::setNumberCompleter(QCompleter *c)
{
m_completerNumber = c;
m_completerNumber->setWidget(this);
connect(m_completerNumber, SIGNAL(activated(QString)),
this, SLOT(insertCompletionNumber(QString)));
}
void ExtendedLineEdit::keyPressEvent(QKeyEvent *e)
{
QLineEdit::keyPressEvent(e);
if (!m_completerWord || !m_completerNumber)
return;
QString lastCaractor = text().mid(text().length() - 1, 1);
bool okConvertion = false;
lastCaractor.toInt(&okConvertion);
if (okConvertion)
{
//show number completer
m_completerWord->popup()->hide();
m_completerNumber->setCompletionPrefix(lastCaractor);
showCustomCompleter(m_completerNumber);
}
else
{
//show word completer
m_completerNumber->popup()->hide();
m_completerWord->setCompletionPrefix(this->text());
showCustomCompleter(m_completerWord);
}
}
void ExtendedLineEdit::insertCompletionWord(const QString &txtComp)
{
setText(txtComp);
}
void ExtendedLineEdit::insertCompletionNumber(const QString &txtComp)
{
setText(text().mid(0, text().length() - 1) + txtComp);
}
void ExtendedLineEdit::showCustomCompleter(QCompleter *completer)
{
if (completer->completionPrefix().length() < 1)
{
completer->popup()->hide();
return;
}
QRect cr = cursorRect();
cr.setWidth(completer->popup()->sizeHintForColumn(0) + completer->popup()->verticalScrollBar()->sizeHint().width());
completer->complete(cr);
}
И используя
QStringList list = { "AAAA","AA","BB","AC" };
m_wordCompleter = new QCompleter(list, this);
QStringList numbers = { "1","2","7", "15" };
m_numberCompleter = new QCompleter(numbers, this);
ui->lineEdit->setWordCompleter(m_wordCompleter);
ui->lineEdit->setNumberCompleter(m_numberCompleter);