c++qtqt5qcompleter

QCompleter with additional result


Need some help. I have a QCompleter with some QStringList, for example:

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

It works fine when user searches in QLineEdit for a word from this list, but I want to show a changed result. For example: user types world and it shows hello world in completer popup.

Is it possible? If yes - how?


Solution

  • First you must place the data in a model, in this case you will use QStandardItemModel, on the other hand to modify the popup you must establish a new delegate, and finally so that when you select an item to be shown in the QLineEdit you must override the pathFromIndex() method :

    #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();
    }