2

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

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

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

是否可以?如果是 - 如何?

4

1 回答 1

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();
}
于 2018-09-24T11:25:02.940 回答