效果如下,在表格的单元格中插入控件,用Delegates方式实现

源代码如下:

main.cpp文件

#include <QApplication>
#include <QStandardItemModel>
#include <QTableView>
#include <QFile>
#include <QTextStream>
#include "datedelegate.h"
#include "combodelegate.h"
#include "spindelegate.h"

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

QStandardItemModel model(4,4);
    QTableView tableView;
    tableView.setModel(&model);

DateDelegate dateDelegate;
    tableView.setItemDelegateForColumn(1,&dateDelegate);

ComboDelegate comboDelegate;
    tableView.setItemDelegateForColumn(2,&comboDelegate);

SpinDelegate spinDelegate;
    tableView.setItemDelegateForColumn(3,&spinDelegate);

model.setHeaderData(0,Qt::Horizontal,QObject::tr("Name"));
    model.setHeaderData(1,Qt::Horizontal,QObject::tr("Birthday"));
    model.setHeaderData(2,Qt::Horizontal,QObject::tr("Job"));
    model.setHeaderData(3,Qt::Horizontal,QObject::tr("Income"));

QFile file("test.tab");
    if(file.open(QFile::ReadOnly|QFile::Text))
    {
        QTextStream stream(&file);
        QString line;

model.removeRows(0,model.rowCount(QModelIndex()),QModelIndex());
        int row =0;
        do{
               line = stream.readLine();
               if(!line.isEmpty())
               {
                   model.insertRows(row,1,QModelIndex());

QStringList pieces = line.split(",",QString::SkipEmptyParts);
                   model.setData(model.index(row,0,QModelIndex()),pieces.value(0));
                   model.setData(model.index(row,1,QModelIndex()),pieces.value(1));
                   model.setData(model.index(row,2,QModelIndex()),pieces.value(2));
                   model.setData(model.index(row,3,QModelIndex()),pieces.value(3));
                   row++;
               }
        }while(!line.isEmpty());

file.close();
    }
    tableView.setWindowTitle(QObject::tr("Delegate"));
    tableView.show();
    return app.exec();
}

datedelegate.h文件

#ifndef DATEDELEGATE_H
#define DATEDELEGATE_H

#include <QItemDelegate>

class DateDelegate : public QItemDelegate
{
   Q_OBJECT

public:
    DateDelegate(QObject *parent = 0);

QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    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 // DATEDELEGATE_H

datedelegate.cpp文件

#include "datedelegate.h"
#include <QDateTimeEdit>

DateDelegate::DateDelegate(QObject *parent) :
    QItemDelegate(parent)
{
}

QWidget *DateDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/*option*/,
const QModelIndex &/*index*/) const
{
    QDateTimeEdit *editor = new QDateTimeEdit(parent);
    editor->setDisplayFormat("yyyy-MM-dd");
    editor->setCalendarPopup(true);
    editor->installEventFilter(const_cast<DateDelegate*>(this));

return editor;
}

void DateDelegate::setEditorData(QWidget *editor,
                                 const QModelIndex &index) const
{
   QString dateStr= index.model()->data(index).toString();
   QDate date = QDate::fromString(dateStr,Qt::ISODate);

QDateTimeEdit *edit=static_cast<QDateTimeEdit*>(editor);
   edit->setDate(date);
}

void DateDelegate::setModelData(QWidget *editor,QAbstractItemModel *model,
                                const QModelIndex &index) const
{
    QDateTimeEdit *edit=static_cast<QDateTimeEdit*>(editor);
    QDate date = edit->date();
    model->setData(index,QVariant(date.toString(Qt::ISODate)));
}

void DateDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

combodelegate.h文件

#ifndef COMBODELEGATE_H
#define COMBODELEGATE_H

#include <QItemDelegate>

class ComboDelegate : public QItemDelegate
{
    Q_OBJECT

public:
    ComboDelegate(QObject *parent = 0);

QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    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 // COMBODELEGATE_H

combodelegate.cpp文件

#include "combodelegate.h"
#include <QComboBox>

ComboDelegate::ComboDelegate(QObject *parent) :
        QItemDelegate(parent)
{
}

QWidget *ComboDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/*option*/,
const QModelIndex &/*index*/) const
{
    QComboBox *editor = new QComboBox(parent);
    editor->addItem(QString::fromLocal8Bit("工人"));
    editor->addItem(QString::fromLocal8Bit("农民"));
    editor->addItem(QString::fromLocal8Bit("医生"));
    editor->addItem(QString::fromLocal8Bit("律师"));
    editor->addItem(QString::fromLocal8Bit("军人"));
    editor->installEventFilter(const_cast<ComboDelegate*>(this));

return editor;
}

void ComboDelegate::setEditorData(QWidget *editor,
                                  const QModelIndex &index) const
{
    QString str =index.model()->data(index).toString();

QComboBox *box = static_cast<QComboBox*>(editor);
    int i=box->findText(str);
    box->setCurrentIndex(i);
}

void ComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                 const QModelIndex &index) const
{
    QComboBox *box = static_cast<QComboBox*>(editor);
    QString str = box->currentText();

model->setData(index,str);
}
void ComboDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const
{
    editor->setGeometry(option.rect);
}

spindelegate.h文件

#ifndef SPINDELEGATE_H
#define SPINDELEGATE_H

#include <QItemDelegate>

class SpinDelegate : public QItemDelegate
{
    Q_OBJECT

public:
    SpinDelegate(QObject *parent = 0);

QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    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 // SPINDELEGATE_H

spindelegate.cpp文件

#include "spindelegate.h"
#include <QSpinBox>

SpinDelegate::SpinDelegate(QObject *parent) :
        QItemDelegate(parent)
{
}

QWidget *SpinDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/*option*/,
const QModelIndex &/*index*/) const
{
    QSpinBox *editor = new QSpinBox(parent);
    editor->setRange(0,10000);
    editor->installEventFilter(const_cast<SpinDelegate*>(this));

return editor;
}

void SpinDelegate::setEditorData(QWidget *editor,
                                  const QModelIndex &index) const
{
    int value =index.model()->data(index).toInt();

QSpinBox *box = static_cast<QSpinBox*>(editor);
    box->setValue(value);
}

void SpinDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                 const QModelIndex &index) const
{
    QSpinBox *box = static_cast<QSpinBox*>(editor);
    int value = box->value();

model->setData(index,value);
}
void SpinDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const
{
    editor->setGeometry(option.rect);
}

http://blog.csdn.net/liuguangzhou123/article/details/7355985

QT代理Delegates使用实例(三种代理控件)的更多相关文章

  1. 三种timer控件的简单实例

    .system.windows.forms .system.threading.timer .system.timers.timer using System; using System.Collec ...

  2. 用Delphi实现文件下载的几种方法(三种使用控件的方法)

    有个API就是UrlDownloadToFile.不仅如此,Delphi的一些控件也可以轻松实现下载,如NMHTTP,指定NMHTTP1.InputFileMode := ture; 指定Body为本 ...

  3. Windows Phone中的几种集合控件

    前言 Windows Phone开发过程中不可避免的就是和集合数据打交道,如果之前做过WP App的开发的话,相信你已经看过了各种集合控件的使用.扩展和自定义.这些个内容在这篇博客里都没有,那么我们今 ...

  4. Java的三种代理模式&完整源码分析

    Java的三种代理模式&完整源码分析 参考资料: 博客园-Java的三种代理模式 简书-JDK动态代理-超详细源码分析 [博客园-WeakCache缓存的实现机制](https://www.c ...

  5. Java的三种代理模式

    Java的三种代理模式 1.代理模式 代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的功能操作,即扩 ...

  6. Java的三种代理模式简述

    本文着重讲述三种代理模式在java代码中如何写出,为保证文章的针对性,暂且不讨论底层实现原理,具体的原理将在下一篇博文中讲述. 代理模式是什么 代理模式是一种设计模式,简单说即是在不改变源码的情况下, ...

  7. 理解java的三种代理模式

    代理模式是什么 代理模式是一种设计模式,简单说即是在不改变源码的情况下,实现对目标对象的功能扩展. 比如有个歌手对象叫Singer,这个对象有一个唱歌方法叫sing(). 1 public class ...

  8. java 的三种代理

    java的三种代理模式   1.代理模式 代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的功能操作, ...

  9. Java的三种代理模式(Spring动态代理对象)

    Java的三种代理模式 1.代理模式 代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的功能操作,即扩 ...

  10. squid 三种代理实验

    squid 软件既可以做代理,也可以做实现缓存加速,大大降低服务器的I/O.. 1.其中squid代理分为三种,正向代理.透明代理.反向代理. (1)squid正向代理和squid透明代理都位客户端: ...

随机推荐

  1. C# 中 int、Convert.ToInt32()、int.Parse()的区别

    int适合简单数据类型之间的转换,C#的默认整型是int32(不支持bool型); int.Parse(string sParameter)是个构造函数,参数类型只支持string类型; Conver ...

  2. 【2017 Multi-University Training Contest - Team 7】Hard challenge

    [Link]:http://acm.hdu.edu.cn/showproblem.php?pid=6127 [Description] 平面上有n个点,每个点有一个价值,每两个点之间都有一条线段,定义 ...

  3. mysql 多实例案例实战

    其实Mysql多实例就是在一个 mysql 服务上面启动三个实例,相当于三个分离开来的数据库,至于为什么要做这个,你也可以选择分别安装三个MySQL,只是过于麻烦,多实例中只需要一个配置档my.cnf ...

  4. method initializationerror not found:JUnit4单元測试报错问题

           今天使用JUnit 4进行单元測试时,測试程序一直执行不起来,报method initializationerror not found错误.例如以下:            网上说版本 ...

  5. HDU 3864 D_num Miller Rabin 质数推断+Pollard Rho大整数分解

    链接:http://acm.hdu.edu.cn/showproblem.php? pid=3864 题意:给出一个数N(1<=N<10^18).假设N仅仅有四个约数.就输出除1外的三个约 ...

  6. JS contcat() 连接数组 函数

    语法: arrayObject.concat(arrayX,arrayX,......,arrayX) 1.把元素添加到数组中 arr.concat(a,b,c);2.把数组连起来 arr.conca ...

  7. css实现水波纹效果

    1. HTML 代码: <div class="example"> <div class="dot"></div> < ...

  8. document.write的注意点

    如果给button点击事件添加document.write会消除页面所有元素,包括button按钮 <!DOCTYPE html> <html> <head> &l ...

  9. Vue里父子组间的通讯

    父组件代码 <template> <div> <child @child-say="listenToBoy" :mes=count></c ...

  10. MWPhotoBrowser 属性详解 和代理解释

    --------0.MWPhoto简单属性解释---------------- MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString: ...