在显示QListView视图时将焦点设置在QLineEdit上

时间:2009-12-17 17:25:11

标签: qt focus qlistview qlineedit

在Qt中,有一个QCompleter类提供自动完成的功能。 我想用QListView来完成同样的事情。在以下代码中,当QListView显示时,QLineEdit将失去焦点。我怎样才能保持QLineEdit的焦点?

1) mdict.h

#include <QtGui/QWidget>

class QLineEdit;
class QListView;
class QModelIndex;

class mdict : public QWidget
{
    Q_OBJECT

public:
    mdict(QWidget *parent = 0);
    ~mdict() {}

private slots:
    void on_textChanged(const QString &);
    void completeText(const QModelIndex &);

private:
    QLineEdit *mLineEdit;
    QListView *mView;
};

2) mdict.cpp

#include <cassert>
#include <QtGui>
#include "mdict.h"

mdict::mdict(QWidget *parent) : QWidget(parent), mLineEdit(0), mView(0)
{
    mLineEdit = new QLineEdit(this);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(mLineEdit);
    layout->addStretch(100);
    setLayout(layout);

    QStringList stringList;
    stringList << "m0" << "m1" << "m2";
    QStringListModel *model = new QStringListModel(stringList);
    mView = new QListView(this);
    mView->setModel(model);
    mView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    mView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    mView->setSelectionBehavior(QAbstractItemView::SelectRows);
    mView->setSelectionMode(QAbstractItemView::SingleSelection);
    mView->setParent(0, Qt::Popup);
    mView->setFocusPolicy(Qt::NoFocus);
    mView->setFocusProxy(mLineEdit);

    connect(mLineEdit, SIGNAL(textChanged(const QString&)), 
        this, SLOT(on_textChanged(const QString &)));
    connect(mView, SIGNAL(activated(const QModelIndex &)),
        this, SLOT(completeText(const QModelIndex &)));
    connect(mView, SIGNAL(clicked(const QModelIndex &)),
        this, SLOT(completeText(const QModelIndex &)));
}

void mdict::on_textChanged(const QString &text)
{
    int lineEidtWidth = mLineEdit->width();
    mView->setMinimumWidth(lineEidtWidth);
    mView->setMaximumWidth(lineEidtWidth);
    mView->setMaximumHeight(60);

    QPoint p(0, mLineEdit->height());
    int x = mLineEdit->mapToGlobal(p).x();
    int y = mLineEdit->mapToGlobal(p).y();
    mView->move(x, y);
    mView->show();
}

void mdict::completeText(const QModelIndex &index)
{
    mLineEdit->setText(index.data().toString());
    mView->hide();
}

3) main.cpp

#include "mdict.h"

#include <QtGui>
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    mdict w;
    w.show();
    return a.exec();
}

1 个答案:

答案 0 :(得分:0)

以这种方式使用Qt::ToolTip代替Qt::Popup

mView->setParent(0, Qt::ToolTip);