如何更改 QCompleter 弹出窗口的顺序?

How to change the order of a QCompleter popup?

我创建了一个自定义 QCompleter class,它在弹出窗口中显示包含 QLineEdit.

的输入单词的所有项目

现在所有项目都按字母顺序排序,如您在此处所见:

如果我输入“dab”然后按字母顺序输入其他项目,我希望弹出窗口显示“dab”作为第一个建议。

我想要这个弹出顺序:

我怎样才能做到这一点?

这是自定义 QCompleter class 我正在使用:

代码

class MyCompleter : public QCompleter
{
    Q_OBJECT

public:
    inline MyCompleter(const QStringList& words, QObject * parent) :
            QCompleter(parent), m_list(words), m_model()
    {
        setModel(&m_model);
    }

    // Filter
    inline void update(QString word)
    {
        // Include all items that contain "word".

        QStringList filtered = m_list.filter(word, caseSensitivity());
        m_model.setStringList(filtered);
        m_word = word;
        complete();
    }

    inline QString word()
    {
        return m_word;
    }

private:
    QStringList m_list;
    QStringListModel m_model;
    QString m_word;
};

我通过创建我的 m_list 的副本并使用 startsWith 函数搜索它来自己完成。然后我将找到的项目添加到 tempList 并像我在问题中所做的那样过滤 c_m_listfiltered 列表也被添加到 tempList

现在看起来像这样:

代码

class MyCompleter : public QCompleter
{
    Q_OBJECT

public:
    inline MyCompleter(const QStringList& words, QObject * parent) :
            QCompleter(parent), m_list(words), m_model()
    {
        setModel(&m_model);
    }

    inline void update(QString word)
    {
        // Include all items that contain "word".
        int idx(0);
        QStringList tempList;
        QStringList c_m_list(m_list);

        while (idx < c_m_list.size())
        {
            if (c_m_list.at(idx).startsWith(word,Qt::CaseInsensitive))
            {
                tempList.append(c_m_list.takeAt(idx--));
            }
            idx++;
        }

        QStringList filtered = c_m_list.filter(word, caseSensitivity());
        c_m_list.sort();

        tempList.append(filtered);

        m_model.setStringList(tempList);
        m_word = word;
        complete();
    }

    inline QString word()
    {
        return m_word;
    }

private:
    QStringList m_list;
    QStringListModel m_model;
    QString m_word;
};

更快的更新功能:

inline void update(QString word)
{
    // Include all items that contain "word".
    QStringList filtered = m_list.filter(word, caseSensitivity());
    QStringList new_list;
    int index = 0;
    while (index < filtered.size()) {
        if (filtered.at(index).startsWith(word, Qt::CaseInsensitive)) {
            new_list.append(filtered.takeAt(index--));
        }
        ++index;
    }
    new_list.append(filtered);

    m_model.setStringList(new_list);
    m_word = word;
    complete();
}