我有一个功能可以实现带有自动完成功能的文本框。
我找到了一个使用 QLineEdit 和 QCompleter 的代码。
因此我有我的字符串值,“一”,“二”,“三”等。
一旦我输入“on”,完成器就会建议我列表中带有前缀“on”的每个单词。
但是当我从列表中选择“一个”并尝试输入第二个单词后,完成器不起作用。
QCompleter 或 Qt 中是否有提供此类功能的功能。我在文档中没有找到它。
查看我找到的代码:
#include <QApplication>
#include<QStringList>
#include<QLineEdit>
#include<QCompleter>
#include<QHBoxLayout>
#include<QWidget>
#include<QLabel>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget *win=new QWidget();
QHBoxLayout *lay=new QHBoxLayout();
QStringList wordList;
wordList << "alpha" << "omega" << "omicron" << "zeta"<<"america"<<"orion"<<"amit"<<"Odssey";
QLabel *lbl=new QLabel("Select");
QLineEdit *lineEdit = new QLineEdit();
lbl->setBuddy(lineEdit);
QCompleter *completer = new QCompleter(wordList);
completer->setCaseSensitivity(Qt::CaseInsensitive); //Make caseInsensitive selectio
lineEdit->setCompleter(completer);
lay->addWidget(lbl);
lay->addWidget(lineEdit);
win->setLayout(lay);
win->showMaximized();
return a.exec();
}
我认为你需要重写 QLineEdit 中的几个方法。我的代码版本:
mclineedit.h
#ifndef MCLINEEDIT_H
#define MCLINEEDIT_H
#include <QLineEdit>
class MCLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit MCLineEdit(QWidget *parent = 0);
void setMultipleCompleter(QCompleter*);
protected:
void keyPressEvent(QKeyEvent *e);
private:
QString cursorWord(const QString& sentence) const;
private slots:
void insertCompletion(QString);
private:
QCompleter* c;
};
#endif // MCLINEEDIT_H
mclineedit.cpp
#include "mclineedit.h"
#include <QCompleter>
#include <QTextCursor>
#include <QAbstractItemView>
#include <QScrollBar>
MCLineEdit::MCLineEdit(QWidget *parent) :
QLineEdit(parent)
{
}
void MCLineEdit::keyPressEvent(QKeyEvent *e)
{
QLineEdit::keyPressEvent(e);
if (!c)
return;
c->setCompletionPrefix(cursorWord(this->text()));
if (c->completionPrefix().length() < 1)
{
c->popup()->hide();
return;
}
QRect cr = cursorRect();
cr.setWidth(c->popup()->sizeHintForColumn(0)
+ c->popup()->verticalScrollBar()->sizeHint().width());
c->complete(cr);
}
QString MCLineEdit::cursorWord(const QString &sentence) const
{
return sentence.mid(sentence.left(cursorPosition()).lastIndexOf(" ") + 1,
cursorPosition() -
sentence.left(cursorPosition()).lastIndexOf(" ") - 1);
}
void MCLineEdit::insertCompletion(QString arg)
{
setText(text().replace(text().left(cursorPosition()).lastIndexOf(" ") + 1,
cursorPosition() -
text().left(cursorPosition()).lastIndexOf(" ") - 1,
arg));
}
void MCLineEdit::setMultipleCompleter(QCompleter* completer)
{
c = completer;
c->setWidget(this);
connect(c, SIGNAL(activated(QString)),
this, SLOT(insertCompletion(QString)));
}
要了解更多信息,请访问http://qt-project.org/doc/qt-4.8/tools-customcompleter.html http://qt-project.org/doc/qt-4.8/tools-customcompleter.html(使用 QTextEdit)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)