简体   繁体   English

将QModelIndex转换为QString

[英]Converting QModelIndex to QString

Is there a way to convert QModelIndex to QString? 有没有办法将QModelIndex转换为QString? The main goal behind this is that I want to work with the contents of dynamically generated QListView-Items. 这背后的主要目标是我想使用动态生成的QListView-Items的内容。

QFileSystemModel *foolist = new QFileSystemModel;
    foolist->setRootPath(QDir::rootPath());
    foolistView->setModel(foolist);

[...]

QMessageBox bar;
QString foolist_selectedtext = foolistView->selectionModel()->selectedIndexes();
bar.setText(foolist_selectedtext);
bar.exec;

Is this even the correct way to get the currently selected Item? 这甚至是获取当前所选项目的正确方法吗?

Thanks in advance! 提前致谢!

foolistView->selectionModel()->selectedIndexes();

Send you back a QList of QModelIndex (only one if you view is in QAbstractItemView::SingleSelection) 发回QModelIndex的QList(如果您在QAbstractItemView :: SingleSelection中查看,则只有一个)

The data method of QModelIndex return a QVariant corresponding to the value of this index. QModelIndex的数据方法返回与该索引的值对应的QVariant。

You can get the string value of this QVariant by calling toString on it. 您可以通过调用toString来获取此QVariant的字符串值。

No, is the short answer. 不,是简短的回答。 A QModelIndex is an index into a model - not the data held in the model at that index. QModelIndex是模型的索引 - 而不是该索引中模型中保存的数据。 You need to call data( const QModelIndex& index, int role = Qt::DisplayRole) const on your model with index being your QModelIndex. 您需要在模型上调用data( const QModelIndex& index, int role = Qt::DisplayRole) constindex为QModelIndex。 If you're just dealing with text the DislayRole should sufficient. 如果您只是处理文本,DislayRole应该足够了。

Yes the way you are getting the selected item is correct, but depending your selection mode, it may return more than one QModelIndex (in a QModelIndexList ). 是的,您获取所选项目的方式是正确的,但根据您的选择模式,它可能会返回多个QModelIndex (在QModelIndexList )。

QModelIndex is identifier of some data structure. QModelIndex是某些数据结构的标识符。 You should read QModelIndex documentation. 您应该阅读QModelIndex文档。 There is a QVariant data(int role) method. 有一个QVariant data(int role)方法。 In most cases you will need Qt::DisplayRole to get selected item text. 在大多数情况下,您需要使用Qt :: DisplayRole来获取所选的项目文本。 Note that also selectIndexes() returns a list of QModelIndex. 请注意,selectIndexes()也返回QModelIndex列表。 It may be empty or contain more then one item. 它可能是空的或包含多个项目。 If you want to get (ie comma separated) texts of all selected indexes you should do something like this: 如果你想得到(即以逗号分隔)所有选定索引的文本,你应该这样做:

QModelIndexList selectedIndexes = foolistView->selectionModel()->selectedIndexes();
QStringList selectedTexts;

foreach(const QModelIndex &idx, selectedIndexes)
{
    selectedTexts << idx.data(Qt::DisplayRole).toString();
}

bar.setText(selectedTexts.join(", "));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM