QTablewidget代理
之前做过一个QTablewidget想要限制某些单元格只能输入IP,刚开始采用在单元格中添加QLineEdit控件的方法,效果差强人意。后来发现通过QItemDelegate可以很方便实现需求。
QItemDelegate
1 #pragma once 2 #include <QWidget> 3 #include <QItemDelegate> 4 #include <QLineEdit> 5 class CIPItem : public
6 { 7 Q_OBJECT 8 public: 9 CIPItem(QObject *parent = 0); 10 ~CIPItem(void); 11 public: 12 QWidget *createEditor ( QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index ) const; 13 void setEditorData ( QWidget * editor, const QModelIndex & index ) const ; 14 void setModelData ( QWidget * editor, QAbstractItemModel * model, const QModelIndex & index ) const ; 15 };
1 #include "IPItem.h" 2 3 CIPItem::CIPItem(QObject *parent):QItemDelegate(parent) 4 { 5 6 } 7 8 CIPItem::~CIPItem(void) 9 { 10 } 11 QWidget *CIPItem::createEditor ( QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index ) const 12 { 13 //添加代理控件 14 QLineEdit *editor = new QLineEdit(parent); 15 QRegExp regExp("\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"); //IP的正则表达式 16 editor->setValidator( new QRegExpValidator(regExp, parent)); 17 return editor; 18 } 19 20 void CIPItem::setEditorData(QWidget *editor, const QModelIndex &index) const 21 { 22 //将单元格中的文本写入代理控件 23 QString text = index.model()->data(index, Qt::EditRole).toString(); 24 QLineEdit *lineEdit = static_cast <QLineEdit*>(editor); 25 lineEdit->setText(text); 26 } 27 28 void CIPItem::setModelData ( QWidget * editor, QAbstractItemModel * model, const QModelIndex & index ) const 29 { 30 //将代理控件的文本写入单元格 31 QLineEdit *lineEdit = static_cast <QLineEdit*>(editor); 32 QString text = lineEdit->text(); 33 model->setData(index, text, Qt::EditRole); 34 }
在QTablewidget中调用setItemDelegate、setItemDelegateForColumn、setItemDelegateForRow即可。