本文介绍了带有QCompleter的QLineEdit不会显示QCompleter的弹出式菜单和空文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个QLineEdit
,与其关联的QCompleter
对象。如果用户输入至少一个字符,则会显示QCompleter
中的弹出菜单,但当用户删除最后一个字符(从而将该字段留空)时,弹出菜单将消失。有没有办法在QLineEdit
的文本为空的情况下也显示它?
推荐答案
使用QCompleter::complete插槽删除行编辑文本后,您应该能够强制显示完成器的弹出窗口:
lineEdit->completer()->complete();
您可以这样做:
- 为您的lineedit定义text已更改槽;
- 重写窗口的CustomEvent方法;
- 在TextChanged槽中,每当Lineedit的文本长度为零;
- 在CustomEvent方法中,每当收到用户事件时显示完成器;
下面是一个示例:
mainwindow.h:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void customEvent(QEvent * event);
private:
Ui::MainWindow *ui;
private slots:
void on_lineEdit_textChanged(QString );
};
mainwindow.cpp:
class CompleteEvent : public QEvent
{
public:
CompleteEvent(QLineEdit *lineEdit) : QEvent(QEvent::User), m_lineEdit(lineEdit) { }
void complete()
{
m_lineEdit->completer()->complete();
}
private:
QLineEdit *m_lineEdit;
};
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QStringList wordList;
wordList << "one" << "two" << "three" << "four";
QLineEdit *lineEdit = new QLineEdit(this);
lineEdit->setGeometry(20, 20, 200, 30);
connect(lineEdit, SIGNAL(textChanged(QString)), SLOT(on_lineEdit_textChanged(QString )));
QCompleter *completer = new QCompleter(wordList, this);
completer->setCaseSensitivity(Qt::CaseInsensitive);
completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
lineEdit->setCompleter(completer);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::customEvent(QEvent * event)
{
QMainWindow::customEvent(event);
if (event->type()==QEvent::User)
((CompleteEvent*)event)->complete();
}
void MainWindow::on_lineEdit_textChanged(QString text)
{
if (text.length()==0)
QApplication::postEvent(this, new CompleteEvent((QLineEdit*)sender()));
}
希望这能有所帮助,致敬
这篇关于带有QCompleter的QLineEdit不会显示QCompleter的弹出式菜单和空文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!