【问题标题】:QCompleter with additional result带有附加结果的 QCompleter
【发布时间】:2018-09-24 10:34:19
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你能解释一下你是怎么得到hello的或者你有什么关系吗?如果您写mouse,您应该返回什么?,您能否更好地解释您的问题。
  • @eyllanesc 我有一个城市列表,并且只想在该列表中进行更完整的搜索,但结果还显示城市类型:用户类型 London,结果显示 town London,或village London等
  • 据我了解,您有一个列表 ["A", "B", "C"] 并且您还有另一个关联列表 ["A1", "B1", "C1"] 和那么如果你选择 A 它应该显示 A1 我正确吗?
  • @eyllanesc 是的,但是 A1 应该显示在弹出窗口中
  • 好的,据我了解,输入了第一个列表的元素,在弹出窗口中必须显示第二个列表的相应元素,现在我的问题是在选择弹出窗口的项目时应该在 QLineEdit 中显示:第一个列表的元素还是第二个?

标签: c++ qt qt5 qcompleter


【解决方案1】:

首先你必须将数据放入模型中,在这种情况下你将使用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();
}

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多