如何将QMouseEvent添加到EventFilter?

时间:2017-08-21 11:47:17

标签: c++ qt eventfilter

我向QCompleter添加了一个EventFilter,因为我和enter image description here人有同样的问题。

现在,如果从PopupCompletion中单击某个项目,我想添加鼠标左键事件。 我试过但我不知道我是否在正确的轨道上,因为我是Qt的新手。

eventfilter.h

class EventFilter : public QObject
{
   Q_OBJECT
public:
   EventFilter(QLineEdit* lineEdit, QObject* parent = NULL)
      :QObject(parent)
      ,mLineEdit(lineEdit)
   { }
   virtual ~EventFilter()
   { }

   bool eventFilter(QObject* watched, QEvent* event);

private:
   QLineEdit* mLineEdit;
};

eventfilter.cpp

#include "eventfilter.h"

bool EventFilter::eventFilter(QObject* watched, QEvent* event)
{
    QAbstractItemView* view = qobject_cast<QAbstractItemView*>(watched);
    if (event->type() == QEvent::KeyPress)
    {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Return ||
            keyEvent->key() == Qt::Key_Enter ||
            keyEvent->key() == Qt::Key_Tab)
        {
            mLineEdit->clear();
            mLineEdit->setFocus();
            view->hide();
            return true;
        }
    }
    if (event->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if (mouseEvent->button() == Qt::LeftButton)
        {
            mLineEdit->clear();
            mLineEdit->setFocus();
            view->hide();
            return true;
        }
    }
    return false;
}

mainwindow.h

#include "eventfilter.h"

class QCompleter;
class QLabel;
class QLineEdit;
class QWidget;

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);

private:
    void createMenu();
    QAbstractItemModel *modelFromFile(const QString& fileName);

    QCompleter *completer;
    QLabel *contentsLabel;
    QLineEdit *lineEdit;
    QWidget *widgetBox;
};

mainwindow.cpp

#include "mainwindow.h"

completer = new QCompleter(this);
completer->setModel(modelFromFile(":/resources/wordlist.txt"));
completer->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
lineEdit->setCompleter(completer);
EventFilter *filter = new EventFilter(lineEdit);
completer->popup()->installEventFilter(filter);

0 个答案:

没有答案