简体   繁体   English

QListView中的QT4 QstringListModel

[英]QT4 QstringListModel in QListView

This is my first QT question - I'm generally a C# programmer so forgive me for asking a stupid question for which I'm sure there's a very simple answer, which I just can't seem to find:这是我的第一个 QT 问题 - 我通常是 C# 程序员,所以请原谅我问了一个愚蠢的问题,我确信有一个非常简单的答案,但我似乎找不到:

I want to add items to a list, for the moment let's say they're strings.我想将项目添加到列表中,暂时假设它们是字符串。 I have a QListView: UI->listView , a QStringList, and a QStringListModel:我有一个 QListView: UI->listView 、一个 QStringList 和一个 QStringListModel:

stringList = new QStringList();
stringList->append("ABC");
stringList->append("123");

listModel = new QStringListModel(*stringList, NULL);
ui->listView->setModel(listModel);

stringList->append("xyz");

This example compiles and disaplys "ABC" and "123" in my list, but not "xyz".这个例子在我的列表中编译并显示“ABC”和“123”,但不是“xyz”。 Why not?为什么不? Do I need to repaint the listView somehow?我需要以某种方式重新绘制 listView 吗? Have I done something wrong with the NULL?我对 NULL 做错了吗?

Thanks.谢谢。

If you frequently need to modify the string list and have connected views that need to be updated, you could consider doing away with the QStringList in the first place and solely using the QStringListModel.如果您经常需要修改字符串列表并且有需要更新的连接视图,您可以考虑首先取消 QStringList 并单独使用 QStringListModel。 You can add/remove data there using insertRows/removeRows and setData.您可以使用 insertRows/removeRows 和 setData 在此处添加/删除数据。 This ensures the views always reflect the model in the way you would expect.这可确保视图始终以您期望的方式反映 model。 This could be wrapped to prevent tedious work.这可以被包装以防止繁琐的工作。 Something like (untested):类似(未经测试):

class StringList : public QStringListModel
{
public:
  void append (const QString& string){
    insertRows(rowCount(), 1);
    setData(index(rowCount()-1), string);
  }
  StringList& operator<<(const QString& string){
    append(string);
    return *this;
  }
};

You've modified the QStringList , you need to modify the model:您已经修改了QStringList ,您需要修改 model:

stringList->append("xyz");
listModel->setStringList(*stringList);

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

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