QCompleter与额外的结果



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

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

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

可能吗?如果是 - 如何?

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

相关内容

  • 没有找到相关文章

最新更新