• 3898阅读
  • 1回复

demo中的一段代码(resolved) [复制链接]

上一主题 下一主题
离线sakiola
 
只看楼主 倒序阅读 楼主  发表于: 2009-08-10
该段代码来自demo中tools/treemodelcompleter

这段代码是用来从已有文件导入数据模型的

有好多地方不懂 请哪位指教下

QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly))
        return new QStringListModel(completer);

#ifndef QT_NO_CURSOR
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
#endif
    QStringList words;

    QStandardItemModel *model = new QStandardItemModel(completer);
    QVector<QStandardItem *> parents(10);
    parents[0] = model->invisibleRootItem();

    while (!file.atEnd()) {
        QString line = file.readLine();
        QString trimmedLine = line.trimmed();
        if (line.isEmpty() || trimmedLine.isEmpty())
            continue;

        QRegExp re("^\\s+");//这个正则表达式是在匹配什么?从字符串起第一个空白符且只匹配一次?是这样吗?如果是的话
                                            //观察输入文件内容(内容见1楼)的格式来看line.trimmed不是把所有的空白符都去掉了吗?
                      //去哪里找这样的字符呢?或者我理解错了?
        int nonws = re.indexIn(line);
        int level = 0;
        if (nonws == -1) {
            level = 0;
        } else {
            if (line.startsWith("\t")) {
                level = re.cap(0).length();
            } else {
                level = re.cap(0).length()/4;
            }
        }

        if (level+1 >= parents.size())
            parents.resize(parents.size()*2);

        QStandardItem *item = new QStandardItem;
        item->setText(trimmedLine);
        parents[level]->appendRow(item);
        parents[level+1] = item;
    }

#ifndef QT_NO_CURSOR
    QApplication::restoreOverrideCursor();
#endif

    return model;
}

总结:失误失误。。。。恼死 line.trimmed修正字符串 却不改变line本身内容 。。。汗死
[ 此帖被sakiola在2009-08-13 10:32重新编辑 ]
NB才是王道
离线sakiola
只看该作者 1楼 发表于: 2009-08-12
上述函数传入的文件内容如下

附resource:treemodel.txt
Parent1
    Child1
        GrandChild1
        GrandChild2
        GrandChild3
            GrandGrandChild1
    Child2
        GrandChild1
            GrandGrandChild1
        GrandChild2
    Child3

Parent2
    Child1
        GrandChild1
    Child2
    Child3
        GrandChild1
        GrandChild2
[ 此帖被sakiola在2009-08-13 10:33重新编辑 ]
NB才是王道
快速回复
限100 字节
 
上一个 下一个