Qt Model/view 小实例 文件目录浏览器

1. 文件目录浏览器

直接在main.cpp文件中添加下列代码

#include "mainwindow.h"

#include <QApplication>
#include <QAbstractItemModel>
#include <QAbstractItemView>
#include <QItemSelectionModel>

#include <QDirModel>
#include <QTreeView>
#include <QListView>
#include <QTableView>
#include <QSplitter>

// MV model view
int main(int argc, char* argv[]) {
    QApplication a(argc, argv);
    //首先创建一个文件模型
    QDirModel model;
    //三种显示模式
    QTreeView tree;
    QListView list;
    QTableView table;
    // 设置view对象的model
    tree.setModel(&model);
    list.setModel(&model);
    table.setModel(&model);
    tree.setSelectionMode(QAbstractItemView::SingleSelection);   //单选
//  tree.setSelectionMode(QAbstractItemView::MultiSelection);   //多选
    list.setSelectionMode(QAbstractItemView::MultiSelection);   //多选
//  table.setSelectionMode(tree.selectionModel());   //多选
    table.setSelectionMode(QAbstractItemView::MultiSelection);   //多选
    QObject::connect(&tree,   SIGNAL(doubleClicked(QModelIndex)), &list, SLOT(setRootIndex(QModelIndex)));
    QObject::connect(&tree,   SIGNAL(doubleClicked(QModelIndex)), &table, SLOT(setRootIndex(QModelIndex)));
    QSplitter* splitter = new QSplitter;
    // 添加布局
    splitter->addWidget(&tree);
    splitter->addWidget(&list);
    splitter->addWidget(&table);
    splitter->setWindowTitle(QObject::tr("Model/View"));
    splitter->show();
    return a.exec();
}

为了实现双击QTreeView对象中的某个目录时,QListView对象和QTableView对象中显示此选定目录下的所有文件和目录,需要连接QTreeView对象的doubleClicked()信号与QListView对象和QTableView对象的setRootIndex()槽函数。

    QObject::connect(&tree,   SIGNAL(doubleClicked(QModelIndex)), &list, SLOT(setRootIndex(QModelIndex)));
    QObject::connect(&tree,   SIGNAL(doubleClicked(QModelIndex)), &table, SLOT(setRootIndex(QModelIndex)));

其中 setRootIndex的介绍如下
在这里插入图片描述

QModelIndex的介绍如下
在这里插入图片描述
QModelIndex类用于定位数据模型中的数据。

doubleClicked信号如下,这个信号不是在tree里面的而是QAbstractItemView里面的
QAbstractItemView::doubleClicked(const QModelIndex &index)

This signal is emitted when a mouse button is double-clicked. The item the mouse was double-clicked on is specified by index. The signal is only emitted when the index is valid.

这个信号在双击鼠标按钮时发出。鼠标双击的项目由index指定。该信号只在索引有效时发出。

2.运行效果

posted @ 2021-07-15 19:48  进击的汪sir  阅读(736)  评论(2编辑  收藏  举报