【问题标题】:Qt: Linking my model data with a QListViewQt:将我的模型数据与 QListView 链接
【发布时间】:2014-07-28 12:12:24
【问题描述】:

我正在编写我的第一个 Qt 项目(所以我是这个环境的新手)并且我已经使用 MVC 设计模式构建了这个项目。 这是一个非常基本的笔记管理器/编辑器。我有一个 uiman 类(“Ui Manager”),它负责我的 UI,以及我打开笔记数据库的功能(这只是一个要打开的文本文件列表)

void uiman::openDBDialog(){

    QFileDialog dialog;
    dialog.setFileMode(QFileDialog::AnyFile);
    dialog.setDirectory("/Users/myuserdir/Desktop");
    dialog.setFilter(QDir::Files);
    dialog.setWindowTitle("Open File");
    dialog.setNameFilter("Textie Notes DB(*.db)");
    dialog.exec();
    QString pathDB = dialog.selectedFiles().first();

    model = new notesModel();
    model->setNotesDB(new QString(pathDB.toUtf8().constData()));
    refreshAll();
}

到目前为止,一切都很好。我采用数据库的路径并将其提供给我的模型,该模型现在应该管理其余部分。 现在,refreshAll() 函数应该获取我打开的列表并将它们显示在我的 QListView 中,但是我无法使用 clear()append() 解析文件并在旅途中附加项目,这与 QListWidget 不同。那么,我该如何从我的文件中构建一个名称向量(我想)并将它们提供给我的 QListView?

对不起,如果我不清楚,但官方文档还不够清楚。

编辑:这是我的模型,nodesmodel,这是代码。

notesModel::notesModel(QObject *parent) :
    QFileSystemModel(parent)
{
    QStringList noteList;

}


void notesModel::setNotesDB(QString *dbpath){
    // open the notes database
    databasepath = dbpath;

}

QFile* notesModel::getDB(){
    if(this->dbFile == NULL)
        this->dbFile = new QFile(databasepath-    >toUtf8().constData());
    return this->dbFile;
}

【问题讨论】:

  • 什么是型号?以及函数 notesModel() 中的内容是什么?
  • 能否请您编辑带有 notesModel 详细信息的帖子。在评论中它们不可读。
  • 抱歉,我的格式有问题,已在主要问题中修复。
  • 请检查此链接是否有帮助:qt-project.org/doc/qt-4.8/…

标签: c++ qt


【解决方案1】:

正如您已经注意到的,您不会从查看器小部件本身添加/删除数据,这是在模型中完成的。

您可以使用 setModel() 方法设置模型。

如果你想显示一个简单的 QString 列表,那么你可以使用:

QStringList strings;
strings << "String 1" << "String 2" << "String 3";
model = new QStringListModel(strings, parent);
view->setModel(model);
// model is managed by parent, and will be deleted when parent is deleted.
// If you create multiple models you might consider other memory management strategy

要读取文本文件并将其行存储在 QStringList 中,请参阅this 答案。

【讨论】:

  • 好的,但是我必须用从文件中读取的列表来提供我的 QStringList。如何将我的数据转换为 QStringList?
  • 这个问题已经在这里问过了,见this answer
  • 非常感谢,但是编译器在“模型”(代码中的第 3 行和第 4 行)处失败,因为它说它是一个未声明的标识符(视图也未声明)。我应该以某种方式实例化它们吗?
  • 您可能应该将模型声明为成员,但如果您只想进行快速测试:QStringListModel model = new QStringListModel(strings,parent);
  • 那行代码带来了“必须调用非静态成员函数的引用”。看来他不喜欢“父母”。
猜你喜欢
  • 2014-10-27
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
  • 2018-07-20
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多