QCompleter具有其他结果

时间:2018-09-24 10:34:19

标签: c++ qt qt5 qcompleter

需要一些帮助。 我有一个QCompleter和一个QStringList,例如:

QstringList list;
list << "world" << "mouse" << "user";

当用户在QLineEdit中搜索此list中的单词时,它工作正常,但我想显示更改的结果。例如:用户键入world,并在完成程序弹出窗口中显示hello world

有可能吗?如果是,怎么办?

1 个答案:

答案 0 :(得分:3)

首先,您必须将数据放置在模型中,在这种情况下,您将使用QStandardItemModel,另一方面,您必须建立一个新的委托来修改弹出窗口,最后,当您选择一个项目来要显示在QLineEdit中,您必须覆盖pathFromIndex()方法:

#include <QApplication>
#include <QCompleter>
#include <QLineEdit>
#include <QStandardItemModel>
#include <QStyledItemDelegate>
#include <QAbstractItemView>

class PopupDelegate: public QStyledItemDelegate
{
public:
    using QStyledItemDelegate::QStyledItemDelegate;
protected:
    void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const
    {
        QStyledItemDelegate::initStyleOption(option, index);
        option->text = index.data(Qt::UserRole+1).toString();
    }
};

class CustomCompleter: public QCompleter
{
public:
    using QCompleter::QCompleter;
    QString pathFromIndex(const QModelIndex &index) const{
        return index.data(Qt::UserRole+1).toString();
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QLineEdit w;

    QStandardItemModel *model = new QStandardItemModel(&w);
    const std::vector<std::pair<QString, QString>> data{ {"London", "town London"},
                                                         {"Moscow", "town Moscow"},
                                                         {"Tokyo", "town Tokyo"}};
    for(const std::pair<QString, QString> & p: data){
        QStandardItem *item = new QStandardItem(p.first);
        item->setData(p.second, Qt::UserRole+1);
        model->appendRow(item);
    }
    CustomCompleter *completer = new CustomCompleter(&w);
    completer->setModel(model);

    PopupDelegate *delegate = new PopupDelegate(&w);
    completer->popup()->setItemDelegate(delegate);
    w.setCompleter(completer);
    w.show();

    return a.exec();
}