美文网首页
Qt DirModel QTreeView

Qt DirModel QTreeView

作者: 静候那一米阳光 | 来源:发表于2017-12-22 00:39 被阅读0次

    QT DirModel QTreeView

    DirModel 增加目录 删除文件目录

    【dialog.h】

    #ifndef DIALOG_H
    #define DIALOG_H
    
    #include <QDialog>
    #include <QDirModel>
    namespace Ui {
    class Dialog;
    }
    
    class Dialog : public QDialog
    {
        Q_OBJECT
    
    public:
        explicit Dialog(QWidget *parent = 0);
        ~Dialog();
    
    private slots:
        void on_pushButton_clicked();
    
        void on_pushButton_2_clicked();
    
    private:
        Ui::Dialog *ui;
        QDirModel *model;
    };
    
    #endif // DIALOG_H
    

    【dialog.cpp】

    #include "dialog.h"
    #include "ui_dialog.h"
    #include <QInputDialog>
    Dialog::Dialog(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::Dialog)
    {
        ui->setupUi(this);
        model=new QDirModel(this);
        model->setReadOnly(false);
        model->setSorting(QDir::DirsFirst|QDir::IgnoreCase|QDir::Name);
        ui->treeView->setModel(model);
    
        QModelIndex index=model->index("/Users/zdy/Desktop");
        ui->treeView->expand(index);
        ui->treeView->scrollTo(index);
        ui->treeView->setCurrentIndex(index);
        ui->treeView->resizeColumnToContents(0);
    }
    
    Dialog::~Dialog()
    {
        delete ui;
    }
    
    void Dialog::on_pushButton_clicked()
    {
        //make dir
        QModelIndex index = ui->treeView->currentIndex();
        if(!index.isValid())return;
        QString name = QInputDialog::getText(this,"Name","Enter a name");
        if(name.isEmpty())return;
        model->mkdir(index,name);
    }
    
    void Dialog::on_pushButton_2_clicked()
    {
        QModelIndex index = ui->treeView->currentIndex();
        //delete
        if(!index.isValid())return;
        if(model->fileInfo(index).isDir()){
            model->rmdir(index);
        }else{
            model->remove(index);
        }
    }
    
    效果图

    相关文章

      网友评论

          本文标题:Qt DirModel QTreeView

          本文链接:https://www.haomeiwen.com/subject/ronzwxtx.html