我正在开发一个基于Qt5的代码编辑器。当我尝试使用QCompleter向编辑器添加自动完成功能时,我发现弹出列表总是出现在编辑区域的底部。如何让它像真正的IDE一样弹出光标的位置?
下面是定义完成器的代码:
QCompleter* HintList = new QCompleter(EditArea);
// EditArea is a QPlainTextEdit item
HintList->setFilterMode(Qt::MatchStartsWith);
HintList->setCompletionMode(QCompleter::PopupCompletion);
QStringListModel* KeyList = new QStringListModel(keywords, this);
// keywords is a QStringList item
HintList->setModel(KeyList);
EditArea->setCompleter(HintList);发布于 2019-09-10 17:21:46
你可以通过编辑器的子类化来实现它。下面是使用QLineEdit的示例
class ExtendedLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit ExtendedLineEdit(QWidget *parent = nullptr);
void setWordCompleter(QCompleter* c);
protected:
void keyPressEvent(QKeyEvent *e);
private slots:
void insertCompletionWord(const QString& txtComp);
private:
QCompleter* m_completerWord;
void showCustomCompleter(QCompleter* completer);
};
void ExtendedLineEdit::setWordCompleter(QCompleter *c)
{
m_completerWord = c;
m_completerWord->setWidget(this);
connect(m_completerWord, SIGNAL(activated(QString)),
this, SLOT(insertCompletionWord(QString)));
}
void ExtendedLineEdit::keyPressEvent(QKeyEvent *e)
{
QLineEdit::keyPressEvent(e);
if (!m_completerWord)
return;
m_completerWord->setCompletionPrefix(this->text());
showCustomCompleter(m_completerWord);
}
void ExtendedLineEdit::insertCompletionWord(const QString &txtComp)
{
setText(txtComp);
}
void ExtendedLineEdit::showCustomCompleter(QCompleter *completer)
{
if (completer->completionPrefix().length() < 1)
{
completer->popup()->hide();
return;
}
//HERE is calculated geometry of completer popup
QRect cr = cursorRect();
cr.setWidth(completer->popup()->sizeHintForColumn(0) + completer->popup()->verticalScrollBar()->sizeHint().width());
completer->complete(cr);
}https://stackoverflow.com/questions/57867277
复制相似问题