实验效果演示:

1
lesson56-build-desktop-Qt_4_7_4___PATH__4_7_4____
lesson56-build-desktop-Qt_4_7_4___PATH__4_7_4____
0x28fe4c
0x28fe4c
F:/Qt/lesson56-build-desktop-Qt_4_7_4___PATH__4_7_4____
lesson56-build-desktop-Qt_4_7_4___PATH__4_7_4____

debug
Makefile
Makefile.Debug
Makefile.Release
release

模型组织数据,然后创建索引,视图通过使用索引访问数据 关系图如下

在这里插入图片描述

索引中的行列结构

在这里插入图片描述

索引中的树状结构

(1)、Root为虚拟节点,用于统一所有数据到同一棵树中
(2)、同一节点的子节点以递增的方式进行编号
(3)、通过(Index,parent)的方式确定节点

在这里插入图片描述
在这里插入图片描述

模型中数据索引的通用方式

(1)、三元组:(row,column,parent)
在这里插入图片描述
在这里插入图片描述
解释

A处于root下面的第0行第0列
B处于A下面的1行第0列
C处于root下面的第2行第1列

如何获得索引

QModelIndex root = m_fsm.index(path);

通过索引又可以得到数据的什么信息?

1. 得到当前相对路径名(文件夹名)
2. 得到路径下的所有文件名
3. 得到绝对路径名

		 QTextStream out(&buffer);
        out << m_fsm.data(root).toString() << endl; // 通过索引得到当前文件夹名(56-1)
        out << root.data().toString() << endl;    //和上面一样
        out << &m_fsm << endl;    //得到地址
        out << root.model() << endl;  //和上面一样
        out << m_fsm.filePath(root) << endl;  //得到路径名
        out << m_fsm.fileName(root) << endl;  //得到当前路径下索引文件名

整体代码如下:

/*Widget.cpp*/
#include "Widget.h"
#include <QDir>
#include <QModelIndex>
#include <QByteArray>
#include <QBuffer>
#include <QTextStream>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    m_edit.setParent(this);
    m_edit.move(10, 10);
    m_edit.resize(500, 300);

    connect(&m_fsm, SIGNAL(directoryLoaded(QString)), this, SLOT(onDirectoryLoaded(QString)));

    m_fsm.setRootPath(QDir::currentPath());
}

void Widget::onDirectoryLoaded(const QString& path)
{
    QModelIndex root = m_fsm.index(path);
    QByteArray array;
    QBuffer buffer(&array);

    if( buffer.open(QIODevice::WriteOnly) )
    {
        QTextStream out(&buffer);

        out << m_fsm.isDir(root) << endl;
        out << m_fsm.data(root).toString() << endl;
        out << root.data().toString() << endl;
        out << &m_fsm << endl;
        out << root.model() << endl;
        out << m_fsm.filePath(root) << endl;
        out << m_fsm.fileName(root) << endl;
        out << endl;

        for(int i=0; i<m_fsm.rowCount(root); i++)
        {
            QModelIndex ci = m_fsm.index(i, 0, root);

            out << ci.data().toString() << endl;
        }

        out.flush();
        buffer.close();
    }

    if( buffer.open(QIODevice::ReadOnly) )
    {
        QTextStream in(&buffer);

        m_edit.insertPlainText(in.readAll());

        buffer.close();
    }
}

Widget::~Widget()
{
    
}

/*Widget.h*/
#ifndef WIDGET_H
#define WIDGET_H

#include <QtGui/QWidget>
#include <QPlainTextEdit>
#include <QFileSystemModel>

class Widget : public QWidget
{
    Q_OBJECT
    
    QPlainTextEdit m_edit;
    QFileSystemModel m_fsm;
protected slots:
    void onDirectoryLoaded(const QString& path);
public:
    Widget(QWidget *parent = 0);
    ~Widget();
};

#endif // WIDGET_H


Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐