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


  • 3
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
QtQTableView添加复选框可以通过自定义一个QItemDelegate来实现。下面是一个简单的示例: 首先,我们定义一个继承自QItemDelegate自定义委托类,名称为CheckBoxDelegate: ```cpp class CheckBoxDelegate : public QItemDelegate { public: CheckBoxDelegate(QObject* parent = nullptr) : QItemDelegate(parent) { } void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override { if (index.column() == 0) { QStyleOptionButton checkBoxOption; checkBoxOption.rect = option.rect; checkBoxOption.state = index.data(Qt::CheckStateRole).toBool() ? QStyle::State_On : QStyle::State_Off; QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkBoxOption, painter); } else { QItemDelegate::paint(painter, option, index); } } QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override { if (index.column() == 0) { QCheckBox* checkBox = new QCheckBox(parent); return checkBox; } else { return QItemDelegate::createEditor(parent, option, index); } } void setEditorData(QWidget* editor, const QModelIndex& index) const override { if (index.column() == 0) { bool checked = index.data(Qt::CheckStateRole).toBool(); QCheckBox* checkBox = static_cast<QCheckBox*>(editor); checkBox->setChecked(checked); } else { QItemDelegate::setEditorData(editor, index); } } void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override { if (index.column() == 0) { QCheckBox* checkBox = static_cast<QCheckBox*>(editor); model->setData(index, checkBox->isChecked(), Qt::CheckStateRole); } else { QItemDelegate::setModelData(editor, model, index); } } }; ``` 然后,在我们的QTableView使用这个自定义委托类来实现复选框的功能: ```cpp QTableView* tableView = new QTableView; QStandardItemModel* model = new QStandardItemModel; // 设置表格大小 model->setRowCount(3); model->setColumnCount(2); // 设置表头 model->setHeaderData(0, Qt::Horizontal, "复选框列"); model->setHeaderData(1, Qt::Horizontal, "其他列"); // 设置复选框数据 model->setData(model->index(0, 0), Qt::Checked, Qt::CheckStateRole); model->setData(model->index(1, 0), Qt::Unchecked, Qt::CheckStateRole); model->setData(model->index(2, 0), Qt::Checked, Qt::CheckStateRole); // 设置委托 CheckBoxDelegate* checkBoxDelegate = new CheckBoxDelegate(tableView); tableView->setItemDelegateForColumn(0, checkBoxDelegate); // 设置数据模型 tableView->setModel(model); ``` 上述代码创建了一个QTableView和一个QStandardItemModel,并通过数据模型设置了3行2列的数据。使用自定义委托类CheckBoxDelegate将第一列的数据设置为复选框。然后将数据模型设置到QTableView。 最后,我们通过`tableView->setModel(model)`将数据模型设置到QTableView完成复选框的添加。 这样就可以在QTableView添加复选框了。记得在使用前先将相应的头文件导入:`#include <QCheckBox>`、`#include <QPainter>`、`#include <QStandardItemModel>`、`#include <QTableView>`、`#include <QItemDelegate>`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值