c – 带有QCompleter的QLineEdit不会显示带有空文本字段的QCompleter弹出菜单

前端之家收集整理的这篇文章主要介绍了c – 带有QCompleter的QLineEdit不会显示带有空文本字段的QCompleter弹出菜单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个QLineEdit,与之关联的QCompleter对象.如果用户输入至少一个字符,则显示QCompleter中的弹出菜单,但是当用户删除最后一个字符(从而使该字段为空)时,弹出窗口消失.即使QLineEdit的文本为空,有没有办法让它显示

解决方法

使用 QCompliter::complete插槽删除行编辑文本后,您应该可以强制完成弹出窗口的显示
lineEdit->completer()->complete();

这是你如何做到的:

>为你的lineedit定义textChanged插槽;
>覆盖窗口的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()));
}

希望这有帮助,问候

原文链接:https://www.f2er.com/c/110871.html

猜你在找的C&C++相关文章