【3】QT视图和委托

作者: 业余玩家 | 来源:发表于2017-01-10 22:06 被阅读230次

    按照本次的学习计划来总结一下今天所学习的一些内容,仍然依据豆子博主所写的关于QT文章进行学习,打算把这个看完之后,再看一下《Qt Quick 核心编程》,学习完之后再进行一个项目制作,然后就结束本次的学习计划。总结的内容一般都是发送出本次学习所用到的完整代码,然后添加自己所遇到的一些问题。

    QFileSystemModel
    //filesystemwidget.h
    #ifndef FILESYSTEMWIDGET_H
    #define FILESYSTEMWIDGET_H
    #include <QDialog>
    #include <QFileSystemModel>
    #include <QTreeView>
    #include <QPushButton>
    #include <QLayout>
    #include <QWidget>
    #include <QInputDialog>
    #include <QMessageBox>
    #include <QHeaderView>
    
    class FileSystemWidget:public QDialog
    {
     Q_OBJECT
    public:
     FileSystemWidget(QWidget *parent=0);
    
    private:
     QFileSystemModel *model;
     QTreeView *treeView;
    private slots:
     void mkdir();
     void rm();
    };
    
    #endif // FILESYSTEMWIDGET_H
    
    //filesystemwidget.cpp
    #include "filesystemwidget.h"
    
    FileSystemWidget::FileSystemWidget(QWidget *parent):QDialog(parent)
    {
     model=new QFileSystemModel;
     model->setRootPath(QDir::currentPath());
    
     treeView=new QTreeView(this);
     treeView->setModel(model);
     treeView->setRootIndex(model->index(QDir::currentPath()));
    
     //设置列头,行头
     treeView->setSortingEnabled(true);//直接加上这个就可以排序了
    
     QPushButton *mkdirButton=new QPushButton(tr("Make Directory..."),this);
     QPushButton *rmButton = new QPushButton(tr("Remove"),this);
     QHBoxLayout *buttonLayout =new QHBoxLayout;
     buttonLayout->addWidget(mkdirButton);
     buttonLayout->addWidget(rmButton);
    
     QVBoxLayout *layout=new QVBoxLayout;
     layout->addWidget(treeView);
     layout->addLayout(buttonLayout);
    
     setLayout(layout);
     setWindowTitle("File System Model");
    
     connect(mkdirButton,SIGNAL(clicked()),this,SLOT(mkdir()));
     connect(rmButton,SIGNAL(clicked()),this,SLOT(rm()));
    }
    
    //创建文件夹
    void FileSystemWidget::mkdir()
    {
     QModelIndex index=treeView->currentIndex();
    
     //IsValid即实例变量的值是否是个有效的对象句柄。
     if(!index.isValid()){
     return;
     }
     QString dirName=QInputDialog::getText(this,tr("Create Directory"),tr("Directory name"));
    
     if(!dirName.isEmpty()){
     if(!model->mkdir(index,dirName).isValid()){
     QMessageBox::information(this,tr("Create Directory"),tr("Failed to create the directory"));
     }
     }
    }
    
    //删除文件
    void FileSystemWidget::rm()
    {
     QModelIndex index=treeView->currentIndex();
     if(!index.isValid()){
     return;
     }
     bool ok;
     if(model->fileInfo(index).isDir()){
     ok=model->rmdir(index);
     }else{
     ok=model->remove(index);
     }
     if(!ok){
     //arg函数用于替换%1
     QMessageBox::information(this,tr("remove"),tr("Failed to remove %1").arg(model->fileName(index)));
     }
    }
    
    //main.cpp
    #include "filesystemwidget.h"
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
     QApplication a(argc, argv);
    
     FileSystemWidget w;
     w.show();
    
     return a.exec();
    }
    
    #QtfileSystemmodel.pro
    QT += core gui
    
    greaterThan(QT_MAJOR_VERSION,4): QT += widgets
    
    TARGET = QtfileSystemmodel
    TEMPLATE = app
    
    SOURCES += main.cpp \
     filesystemwidget.cpp
    
    HEADERS += \
     filesystemwidget.h
    

    备注:为什么把pro文件发送出来呢?因为本次代码我创建的是控制台应用程序,那么想要运行出窗口就需要改一下这个pro文件,主要是添加gui和widgets。上午代码总是运行不了,花了好长时间,才发现是QApplication没有改过来,控制台程序下它是QCoreApplication,这个我找了半天,太尴尬了。

    视图和委托
    //listview.h
    #ifndef LISTVIEW_H
    #define LISTVIEW_H
    #include <QStringList>
    #include <QStringListModel>
    #include <QListView>
    #include <QPushButton>
    #include <QLayout>
    #include <QDialog>
    
    class ListView:public QDialog
    {
     Q_OBJECT
    public:
     ListView();
    
    private:
     QStringListModel *model;
     QListView *listView;
    
    private slots:
     void showModel();
    };
    
    #endif // LISTVIEW_H
    
    //spinboxdelegate.h
    #ifndef SPINBOXDELEGATE_H
    #define SPINBOXDELEGATE_H
    
    #include <QStyledItemDelegate>
    
    class SpinBoxDelegate:public QStyledItemDelegate
    {
    public:
     SpinBoxDelegate(QObject *parent=0):QStyledItemDelegate(parent){}
    
     //createEditor():返回一个组件。该组件会被作为用户编辑数据时所使用的编辑器,从模型中接受数据,返回用户返回的数据
     QWidget *createEditor(QWidget *parent,const QStyleOptionViewItem &option,const QModelIndex &index) const;
    
     //setEditorData():提供上述组建在显示时所需要的默认值
     void setEditorData(QWidget *editor,const QModelIndex &index)const;
     //返回给模型用户修改过的数据
     void setModelData(QWidget *editor,QAbstractItemModel *model,const QModelIndex &index) const;
     //确保上述组件作为编辑器是能够完整地显示出来。
     void updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option,const QModelIndex &index) const;
    };
    
    #endif // SPINBOXDELEGATE_H
    
    //listview.cpp
    #include "listview.h"
    #include "spinboxdelegate.h"
    
    ListView::ListView():QDialog()
    {
     QStringList data;
     data<<"0"<<"1"<<"2";
     model=new QStringListModel();
     model->setStringList(data);
    
     listView=new QListView();
     listView->setModel(model);
     //使用委托
     listView->setItemDelegate(new SpinBoxDelegate(listView));
    
     QPushButton *btnShow=new QPushButton(tr("Show Model"));
     connect(btnShow,SIGNAL(clicked()),this,SLOT(showModel()));
    
     QHBoxLayout *buttonLayout=new QHBoxLayout;
     buttonLayout->addWidget(btnShow);
    
     QVBoxLayout *layout=new QVBoxLayout;
     layout->addWidget(listView);
     layout->addLayout(buttonLayout);
    
     setLayout(layout);
    }
    
    void ListView::showModel()
    {
    
    }
    
    //spinboxdelegate.cpp
    #include "spinboxdelegate.h"
    #include <QSpinBox>
    
    QWidget *SpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const
    {
     QSpinBox *editor=new QSpinBox(parent);
     editor->setMinimum(0);
     editor->setMaximum(100);
     return editor;
    }
    
    void SpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
    {
     int value=index.model()->data(index,Qt::EditRole).toInt();
     //static_cast<type-id>(expression)该运算符把expression转换为type-id类型,但没有运行时类型检查来保证转换的安全性。
     QSpinBox *spinBox=static_cast<QSpinBox*>(editor);
     spinBox->setValue(value);
    }
    
    void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
    {
     QSpinBox *spinBox=static_cast<QSpinBox*>(editor);
     spinBox->interpretText();
     int value=spinBox->value();
     model->setData(index,value,Qt::EditRole);
    }
    
    void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
     editor->setGeometry(option.rect);
    }
    
    //main.cpp
    #include <QApplication>
    #include "listview.h"
    
    int main(int argc, char *argv[])
    {
     QApplication a(argc, argv);
     ListView w;
     w.show();
     return a.exec();
    }
    

    备注:在 model/view 架构中,视图是数据从模型到最终用户的途径。数据通过视图向用户进行显示。
    委托供视图实现某种高级的编辑功能。
    委托的接口由QAbstractItemDelegate定义。在这个类中,委托通过paint()
    和sizeHint()两个函数渲染用户内容(也就是说,你必须自己将渲染器绘制出来)。为使用方便,从 4.4 开始,Qt 提供了另外的基于组件的子类:QItemDelegate和QStyledItemDelegate,默认的委托是QStyledItemDelegate。

    视图选择
    //main.cpp
    #include <QApplication>
    #include <QTableWidget>
    
    int main(int argc, char *argv[])
    {
     QApplication a(argc, argv);
    
     QTableWidget *tableWidget=new QTableWidget(8,4);
    
     //选择单元格
     QItemSelectionModel *selectionModel=tableWidget->selectionModel();
     QModelIndex topLeft=tableWidget->model()->index(0,0,QModelIndex());
     QModelIndex bottomRight=tableWidget->model()->index(5,2,QModelIndex());
     //设为选区
     QItemSelection selection(topLeft,bottomRight);
     //select()函数的第一个参数就是需要选择的选区,第二个参数是选区的标  志位。
     selectionModel->select(selection,QItemSelectionModel::Select);
    
     //获得选区
     QModelIndexList indexes=selectionModel->selectedIndexes();
     QModelIndex index;
    
     foreach (index, indexes) {
     QString text=QString("(%1,%2)").arg(index.row()).arg(index.column());
     //model->setData(index,text);
     }
    
     QItemSelection toggleSelection;
    
     topLeft=tableWidget->model()->index(2,1,QModelIndex());
     bottomRight=tableWidget->model()->index(7,3,QModelIndex());
     toggleSelection.select(topLeft,bottomRight);
    
     //对前面的取反操作
     selectionModel->select(toggleSelection,QItemSelectionModel::Toggle);
    
     QItemSelection columnSelection;
    
     topLeft=tableWidget->model()->index(0,1,QModelIndex());
     bottomRight=tableWidget->model()->index(0,2,QModelIndex());
     columnSelection.select(topLeft,bottomRight);
     //整列选取
     selectionModel->select(columnSelection,QItemSelectionModel::Select | QItemSelectionModel::Columns);
    
     QItemSelection rowSelection;
     topLeft=tableWidget->model()->index(0,0,QModelIndex());
     bottomRight=tableWidget->model()->index(1,0,QModelIndex());
     rowSelection.select(topLeft,bottomRight);
    
     //整行选取
     selectionModel->select(rowSelection,QItemSelectionModel::Select | QItemSelectionModel::Rows);
    
     tableWidget->show();
     return a.exec();
    }
    

    备注:QT中使用QItemSelectionModel类获取视图中项目的选择情况。如果需要创建一个选区,我们需要指定一个模型以及一对索引,使用这些数据创建一个QItemSelection对象。

    今天的学习也就到这里就结束了,天气寒冷都不想起床了,为早起的人儿致敬……

    相关文章

      网友评论

        本文标题:【3】QT视图和委托

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