【3】QT视图和委托

按照本次的学习计划来总结一下今天所学习的一些内容,仍然依据豆子博主所写的关于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对象。

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容