QT:在QTableView中使用各种自定义委托_qtableview setitemdelegate-程序员宅基地

技术标签: QItemDelegate  Qt  Qt代理  QTableView  

QT的MVC(View/Delegate)模型十分强大,可以利用各种控件来对表格的输入进行限制,不过我以前一直没有过,这几天研究了一下,写个小例子,希望大家喜欢。

如果看不懂这个例子,请先看QT的自带例子: http://qt-project.org/doc/qt-4.8/itemviews-spinboxdelegate.html

思路:

1:为每一列定义委托:
A:第一列是编号列,使用只读委托,令该列的单元格是只读的
B:第三列是ID列,只能输入1-12个数字,利用QLineEdit委托和正则表达式对输入进行限制
C:第四年龄列,利用QSpinBox委托进行输入限制,只能输入1-100之间的数字
D:第五列是性别列,利用QComboBox委托对输入进行限制,该列的单元格只能输入Male或Female
E:第六列是头像列,在该列的单元格中央放置一张头像
2:定义代理类,把所有单元格中的字符居中显示。

3:利用QSS,将表格的背景色弄成黄蓝相间。


截图:


源代码:

tool.h

#ifndef TOOL_H
#define TOOL_H
#include <QtGui>

//编号列,只读委托
//这个方法我还真想不到,呵呵
class  ReadOnlyDelegate :  public  QItemDelegate
{
    Q_OBJECT
public :
    ReadOnlyDelegate(QObject *parent = 0): QItemDelegate(parent) { }
    QWidget *createEditor(QWidget*parent,  const QStyleOptionViewItem &option,
         const  QModelIndex &index)  const
    {
         return  NULL;
    }
};

//ID列,只能输入1-12个数字
//利用QLineEdit委托和正则表达式对输入进行限制
class  UserIDDelegate :  public  QItemDelegate
{
    Q_OBJECT
public :
    UserIDDelegate(QObject *parent = 0): QItemDelegate(parent) { }
    QWidget *createEditor(QWidget *parent,  const QStyleOptionViewItem &option,
         const  QModelIndex &index)  const
    {
        QLineEdit *editor =  new  QLineEdit(parent);
        QRegExp regExp( "[0-9]{0,10}" );
        editor->setValidator( new  QRegExpValidator(regExp, parent));
         return  editor;
    }
     void  setEditorData(QWidget *editor,  const  QModelIndex &index)  const
    {
        QString text = index.model()->data(index, Qt::EditRole).toString();
        QLineEdit *lineEdit =  static_cast <QLineEdit*>(editor);
        lineEdit->setText(text);
    }
     void  setModelData(QWidget *editor, QAbstractItemModel *model,
         const  QModelIndex &index)  const
    {
        QLineEdit *lineEdit =  static_cast <QLineEdit*>(editor);
        QString text = lineEdit->text();
        model->setData(index, text, Qt::EditRole);
    }
     void  updateEditorGeometry(QWidget *editor,
         const  QStyleOptionViewItem &option,  const  QModelIndex &index) const
    {
        editor->setGeometry(option.rect);
    }
};

//年龄列,利用QSpinBox委托进行输入限制,只能输入1-100之间的数字
class  AgeDelegate :  public  QItemDelegate
{
    Q_OBJECT
public :
    AgeDelegate(QObject *parent = 0): QItemDelegate(parent) { }
    QWidget *createEditor(QWidget *parent,  const QStyleOptionViewItem &option,
         const  QModelIndex &index)  const
    {
        QSpinBox *editor =  new  QSpinBox(parent);
        editor->setMinimum(1);
        editor->setMaximum(100);
         return  editor;
    }
     void  setEditorData(QWidget *editor,  const  QModelIndex &index)  const
    {
         int  value = index.model()->data(index, Qt::EditRole).toInt();
        QSpinBox *spinBox =  static_cast <QSpinBox*>(editor);
        spinBox->setValue(value);
    }
     void  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  updateEditorGeometry(QWidget *editor,
         const  QStyleOptionViewItem &option,  const  QModelIndex &index) const
    {
        editor->setGeometry(option.rect);
    }
};

//性别列,利用QComboBox委托对输入进行限制
//这一列的单元格只能输入Male或Female
class  SexDelegate :  public  QItemDelegate
{
    Q_OBJECT
public :
    SexDelegate(QObject *parent = 0): QItemDelegate(parent) { }
    QWidget *createEditor(QWidget *parent,  const QStyleOptionViewItem &option,
         const  QModelIndex &index)  const
    {
        QComboBox *editor =  new  QComboBox(parent);
        editor->addItem( "Female" );
        editor->addItem( "Male" );
         return  editor;
    }
     void  setEditorData(QWidget *editor,  const  QModelIndex &index)  const
    {
        QString text = index.model()->data(index, Qt::EditRole).toString();
        QComboBox *comboBox =  static_cast <QComboBox*>(editor);
         int  tindex = comboBox->findText(text);
        comboBox->setCurrentIndex(tindex);
    }
     void  setModelData(QWidget *editor, QAbstractItemModel *model,
         const  QModelIndex &index)  const
    {
        QComboBox *comboBox =  static_cast <QComboBox*>(editor);
        QString text = comboBox->currentText();
        model->setData(index, text, Qt::EditRole);
    }
     void  updateEditorGeometry(QWidget *editor,
         const  QStyleOptionViewItem &option,  const  QModelIndex &index) const
    {
        editor->setGeometry(option.rect);
    }
};

//头像列,只是在单元格中央放一张小图而已
class  IconDelegate :  public  QItemDelegate
{
    Q_OBJECT
public :
    IconDelegate(QObject *parent = 0): QItemDelegate(parent) { }
     void  paint(QPainter *painter,  const  QStyleOptionViewItem &option,
         const  QModelIndex & index )  const
    {
         //show.bmp是在工程目录中的一张图片(其实就是QQ的图标啦,呵呵)
        QPixmap pixmap = QPixmap( "/temp/lengshuiji.png" ).scaled(24, 24);
        qApp->style()->drawItemPixmap(painter, option.rect,  Qt::AlignCenter, QPixmap(pixmap));
    }
};

//代理类,把所有单元格中的字符居中显示
class  VIPModel :  public  QStandardItemModel
{
    Q_OBJECT
public :
    VIPModel(QObject *parent=NULL) : QStandardItemModel(parent) { }
    VIPModel( int  row,  int  column, QObject *parent=NULL)
        : QStandardItemModel(row, column, parent) { }
    QVariant data( const  QModelIndex &index,  int  role = Qt::DisplayRole) const
    {
         if ( Qt::TextAlignmentRole == role )
             return  Qt::AlignCenter;
         return  QStandardItemModel::data(index, role);
    }

};


#endif // TOOL_H


main.cpp

#include <QtGui/QApplication>
#include "tool.h"


int  main( int  argc,  char  *argv[])
{
    QApplication app(argc, argv);

    VIPModel *model =  new  VIPModel(5, 5);
    QTableView *tableView =  new  QTableView;

     //把表格的背景调成黄蓝相间
     //这种方法是在网上看到的,用起来还真方便啊
    tableView->setAlternatingRowColors( true );
    tableView->setStyleSheet( "QTableView{background-color: rgb(250, 250, 115);"
         "alternate-background-color: rgb(141, 163, 215);}" );

    tableView->setWindowTitle( "VIP List" );
    tableView->resize(700, 400);
    tableView->setModel(model);
    QStringList headerList;
    headerList <<  "No."  <<  "ID"  <<  "Name"  <<  "Age"  <<  "Sex"  <<  "Show" ;
    model->setHorizontalHeaderLabels(headerList);
    tableView->verticalHeader()->setVisible( false );
    tableView->horizontalHeader()->setStretchLastSection( true );

     //为每一列加载委托
    ReadOnlyDelegate readOnlyDelegate;
    tableView->setItemDelegateForColumn(0, &readOnlyDelegate);
    UserIDDelegate userIDDelegate;
    tableView->setItemDelegateForColumn(1, &userIDDelegate);
    AgeDelegate spinBoxDelegate;
    tableView->setItemDelegateForColumn(3, &spinBoxDelegate);
    SexDelegate comboBoxDelegate;
    tableView->setItemDelegateForColumn(4, &comboBoxDelegate);
    IconDelegate iconDelegate;
    tableView->setItemDelegateForColumn(5, &iconDelegate);

     for ( int  i=0; i<10; i++)
    {
        QModelIndex index = model->index(i, 0, QModelIndex());
        model->setData(index, i);
    }

    tableView->show();
     return  app.exec();
}


转载自:http://blog.csdn.net/lhchen922/article/details/38367719


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zgrjkflmkyc/article/details/48086851

智能推荐

Sklearn中predict_proba函数用法及原理详解-程序员宅基地

文章浏览阅读4k次,点赞3次,收藏11次。Sklearn中predict_proba函数用法及数学原理详解(以logistic回归为例)_predict_prob

MVCC解决什么问题?原理是什么?_mvcc解决了什么问题-程序员宅基地

文章浏览阅读1.4k次。MVCC解决什么问题?原理是什么?_mvcc解决了什么问题

(邱维声)高等代数课程笔记:解线性方程组的矩阵消元法_比较消元法和初等变换求线性方程组的异同,并阐述自己的收获-程序员宅基地

文章浏览阅读383次。根据邱维声老师的高等代数课程,整理的笔记。_比较消元法和初等变换求线性方程组的异同,并阐述自己的收获

android商城首页demo,FanZhengxi-程序员宅基地

文章浏览阅读281次。Android HyBridge 开发一、三种App开发方式对比1. Native App特点:UI元素、数据内容、逻辑架构都安装在手机终端,导致不可跨平台,每次版本升级都要重新打包。缺点:无法跨平台、升级麻烦、开发成本高(指跨平台开发成本高)优点:速度快,用户体验好。2. Web App定义:可理解为移动端的网站,将网页部署在服务器上,用户通过各大浏览器来访问。缺点:页面访问速度慢、用户体验差。..._安卓应用商店app demo

好烦!快让ChatGPT停止道歉!SD创作宣传图的超细教程;教你在PH冷启动薅流量;CSDN举办AI应用创新大赛 | ShowMeAI日报_inscode deecamp x csdn ai应用创新大赛-程序员宅基地

文章浏览阅读318次。Stable Diffusion 图生图知识思维导图;使用 5W1H 框架启动一个可控的AI项目;培生集团将生成式AI学习工具引入在线高等教育平台;前 Meta AI 高管离职创业,做教育类 ChatGPT 应用……点击阅读全文_inscode deecamp x csdn ai应用创新大赛

【21天算法挑战赛】查找算法——顺序查找_普通查找是顺序查找么-程序员宅基地

文章浏览阅读814次,点赞9次,收藏7次。作者简介:我目前是一个在校学生,现在不敢说自己擅长什么,但是我想通过自己的学习努力让自己的技术、知识都慢慢提升,希望我们一起学习呀~。有话想说:写博客、记笔记并不是一种自我感动,把学到的东西记在脑子里才是最重要的,在这个过程中,不要浮躁,希望我们都可以越来越优秀!由于算法不会改变原有的元素集合,只需要一个额外的变量控制索引变化,所以空间复杂度为常数级:O(1)️兴趣领域:目前偏向于前端学习 算法学习。语言说明:代码实现我会用Python/C++~空间复杂度:O(1)

随便推点

Debruijn问题 超星吉林大学高级程序设计作业-程序员宅基地

文章浏览阅读353次,点赞2次,收藏5次。Debruijn问题 超星作业题目描述:输入输出要求:解题:备注:题目描述:输入输出要求:输入:n(n<=4)输出:按照字典序输出符合的答案(当出现多组本质不同的解时,仅输出字典序中最小的那个序列);每行数字间以一个西文空格间隔,行末有一个换行符。样例1:输入:3输出:0 0 0 1 0 1 1 1解题://准备#include<stdio.h>#include<math.h>int m[16]={0}; //数组 int fl_debruijn

JAVA常用实用类-程序员宅基地

文章浏览阅读1.1k次,点赞33次,收藏21次。javaAPI(java Application Programming Interface)即java应用程序编程接口,它是运行库的集合,预先定义了一些接口和类,程序员可以直接使用这些已经被打包的接口和类开发具体的应用来节约大量的时间和精力。API除了有"应用程序编程接口"的意思,还特指API的说明文档,也被称为API帮助文档。java语言的强大之处在于它提供了多种多样的类库,从而大大提高了程序的编程效率和质量,javaAPI提供常用的包如下。

常见python库学习(一)Tkinter库_GUI界面设计_python窗体类库-程序员宅基地

文章浏览阅读541次。提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录前言一、tkinter窗口1.简介2.Tkinter 控件二、1.引入库2.读入数据总结前言提示:这里可以添加本文要记录的大概内容:例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。提示:以下是本篇文章正文内容,下面案例可供参考一、tkinter窗口1.简介Tkinter 是使用 python 进行窗口视窗设计的模块,是 python 自带的、可_python窗体类库

通过mtd读写flash_基于STM32F7通过cube软件配置:读写QSPI接口64M flash和64M PSRAM参考教程...-程序员宅基地

文章浏览阅读825次。基于STM32F7通过cube软件配置:读写QSPI接口64M flash和64M PSRAM参考教程核心板:NUCLEO-F767ZIFlash:NM25Q64EB(64M)PSRAM:IPS6404L(64M)配置文件请使用stm32cubemx打开程序请使用keil5MDK打开NUCLEO-F767ZI上引出的QSPI引脚如下,NM25Q64EB和IPS6404L都是分别接到同样..._stm32f7 单片机 64引脚

获取栅格图层(Raster)的属性表_r raster getvalue-程序员宅基地

文章浏览阅读388次。pNewRaster是你的Raster图层IRasterBandCollection pRasterBC =(IRasterBandCollection ) pNewRaster;IRasterBand pRasterBand = pRasterBC.Item(0);ITable pTable = pRasterBand.AttributeTable;IQueryFilter pQueryFilter=new QueryFilterClass ();pQueryFilter .WhereClau._r raster getvalue

python反编译class文件_python反编译之字节码-程序员宅基地

文章浏览阅读226次。如果你曾经写过或者用过 Python,你可能已经习惯了看到 Python 源代码文件;它们的名称以.Py 结尾。你可能还见过另一种类型的文件是 .pyc 结尾的,它们就是 Python “字节码”文件。(在 Python3 的时候这个 .pyc 后缀的文件不太好找了,它在一个名为__pycache__的子目录下面。).pyc文件可以防止Python每次运行时都重新解析源代码,该文件大大节省了时间。..._python反编译class文件

推荐文章

热门文章

相关标签