c++ - 带有附加结果的 QCompleter

标签 c++ qt qt5 qcompleter

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

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

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

这可能吗?如果是 - 如何?

最佳答案

首先你必须将数据放在一个模型中,在这种情况下你将使用QStandardItemModel,另一方面要修改弹出窗口你必须建立一个新的委托(delegate),最后这样当你选择要在 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();
}

关于c++ - 带有附加结果的 QCompleter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52477443/

相关文章:

c++ - 为什么 vector 分配会改变分配的 vector

c++ - 如何在我的 makefile 中包含目录及其所有子目录的 header ?

c++ - 类成员在其他类中充当友元 C++

c++ - 用 QLinearGradient 绘制 QPushButton

qt - 用户界面形式 : Add runtime or compile time?

c++ - 删除和释放 QGraphicsItem 类派生对象

c++方法有时会返回意外的高值

c++ - 通过 QT C++ 连接到 SQL Server 2005

linux - python 和 qt5 的 Yocto 构建错误

c++ - Qt:强制QDockWidget的大小