QT4 QstringListModel in QListView

QT4 QstringListModel in QListView

本文关键字:QListView in QstringListModel QT4      更新时间:2023-10-16

这是我的第一个QT问题-我通常是一个c#程序员,所以请原谅我问了一个愚蠢的问题,我确信有一个非常简单的答案,我只是似乎找不到:

我想向列表中添加元素,现在我们假设它们是字符串。我有一个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");

这个例子在我的列表中编译并显示"ABC"answers"123",但不显示"xyz"。为什么不呢?我需要重新绘制listView吗?我做了什么错误的NULL?

谢谢。

如果您经常需要修改字符串列表,并且有需要更新的连接视图,那么您可以考虑首先取消QStringList并单独使用QStringListModel。你可以使用insertRows/removeRows和setData在那里添加/删除数据。这确保视图总是以您期望的方式反映模型。可以对其进行包装,以避免繁琐的工作。类似(未测试):

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;
  }
};

您已经修改了QStringList,您需要修改模型:

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