【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对象。

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的QT视图模型委托项目案例: 假设有一个表格,其中一列显示了用户的年龄,我们想要让年龄小于18岁的行以红色显示,而年龄大于等于18岁的行以绿色显示。我们可以通过使用QT视图模型委托来实现此目的。 首先,我们需要定义一个自定义的委托类,该类继承自QStyledItemDelegate类。在该类中,我们将实现一个paint()函数,该函数将会在每次需要绘制表格项时被调用。 ```cpp class AgeDelegate : public QStyledItemDelegate { public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override { // 获取年龄值 int age = index.data(Qt::DisplayRole).toInt(); // 设置画笔颜色 if (age < 18) { painter->setPen(QColor("red")); } else { painter->setPen(QColor("green")); } // 调用基类的paint()函数进行绘制 QStyledItemDelegate::paint(painter, option, index); } }; ``` 接下来,我们需要在主窗口中创建一个表格,并为其设置一个QStandardItemModel模型。然后,我们将会为该模型的第二列(即年龄列)设置我们刚刚定义的委托类。 ```cpp // 创建表格和模型 QTableView *tableView = new QTableView(this); QStandardItemModel *model = new QStandardItemModel(4, 2, this); // 设置表头 model->setHeaderData(0, Qt::Horizontal, tr("Name")); model->setHeaderData(1, Qt::Horizontal, tr("Age")); // 设置模型数据 model->setData(model->index(0, 0), "John Doe"); model->setData(model->index(0, 1), 25); model->setData(model->index(1, 0), "Jane Smith"); model->setData(model->index(1, 1), 17); model->setData(model->index(2, 0), "Bob Johnson"); model->setData(model->index(2, 1), 30); model->setData(model->index(3, 0), "Mary Williams"); model->setData(model->index(3, 1), 16); // 为模型的第二列设置委托 tableView->setItemDelegateForColumn(1, new AgeDelegate(this)); // 将模型设置给表格 tableView->setModel(model); ``` 现在,我们运行程序,就可以看到表格中年龄小于18岁的行以红色显示,而年龄大于等于18岁的行以绿色显示。这就是通过QT视图模型委托实现的。 注意:本示例并不完整,只是为了演示视图模型委托的基本用法。在实际应用中,您可能需要对上述代码进行进一步的修改和完善。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值