简体   繁体   English

如何在QT中正确显示std :: vector?

[英]How to show std::vector in QT properly?

I have small class "Dictionary", where I contain all data in std::vector. 我有一个小类“ Dictionary”,其中所有数据都包含在std :: vector中。 I want to show this data in QT application. 我想在QT应用程序中显示此数据。 So I did a small research and I found that I should use ListView like this: 因此,我做了一个小型研究,发现应该像这样使用ListView:

ui->WordList->setModel(new QStringListModel(QList<QString>::fromVector
                                            (dict->getQVector())));

But this looks like really show. 但这看起来确实很有趣。 I have to update model of ListView each time I add new element to vector. 每次向vector添加新元素时,我都必须更新ListView的模型。 And also I have to add function to my Dictionary class to get QVector: 而且我还必须向Dictionary类添加函数以获得QVector:

QVector<QString> getQVector() {
  QVector<QString> qv;
  for (size_t i = 0; i < container.size(); i++) {
      qv.push_back(QString::fromStdString((std::string)container[i]));
  }
  return qv;
  }

...and this looks also really slow. ...而且看起来也真的很慢。 So I have a question: should I rewrite my Dictionary class using QTL? 所以我有一个问题:是否应该使用QTL重写Dictionary类? If so, how to display QVector using ListView (or maybe something else) in convenient way? 如果是这样,如何以便捷的方式使用ListView(或其他方式)显示QVector? Thanks in advance. 提前致谢。

Without knowing all of your requirements for your Dictionary class, my suggestion would be to replace the internal std::vector with a QStringListModel, and then set that as your model for your view. 在不知道您对Dictionary类的所有要求的情况下,我的建议是将内部std :: vector替换为QStringListModel,然后将其设置为视图的模型。 When you make a change to the QStringListModel, it will be reflected in your view automatically. 当您对QStringListModel进行更改时,它将自动反映在您的视图中。

Alternately, make your Dictionary class a model by subclassing it from QAbstractItemModel. 或者,通过从QAbstractItemModel继承子类,使Dictionary类成为模型。 You could still keep your std::vector as the internal data structure and then your "data" and "setData" methods would read from and write to the std::vector. 您仍然可以将std :: vector保留为内部数据结构,然后您的“ data”和“ setData”方法将读取和写入std :: vector。

Without knowing more about what your Dictionary is for, whether it's sorted or not, whether it contains duplicate entries or not, and so on, it's hard to make solid recommendations on an appropriate data structure. 如果不了解字典的用途,是否进行排序,是否包含重复的条目等等,就很难对适当的数据结构提出可靠的建议。

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

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