QT tableview内置控件

为什么需要内置控件 tableview 默认的内置控件是QLineEdit,但是实际使用时,我们常常会有特殊需求,例如对QLineEdit有字数限制,性别有固定的选项等等,因此我们需要自定义tableview的内置控件
代码 下面的例子中,我使用了两个内置控件,你们可以根据需要自行修改,依旧先上运行图,再上代码
此处对性别栏内置了combo,对爱好栏内置了QTextEdit
QT tableview内置控件
文章图片

tabviewDelegate.h

#include #include #include class tabviewDelegate: public QItemDelegate { Q_OBJECT public: tabviewDelegate(QObject *parent = 0); public: 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; public: QString type; //根据type来控制选中时激活的是那种控件};

tabviewDelegate.cpp
#include "tabviewDelegate.h"#include tabviewDelegate::tabviewDelegate(QObject *parent) {}QWidget *tabviewDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { qDebug()<<"createEditor"; if(type == "sex") { QComboBox *editor = new QComboBox(parent); editor->addItem(tr("男")); editor->addItem(tr("女")); return editor; } else { QTextEdit *editor = new QTextEdit(parent); return editor; }}//设置editor数据 void tabviewDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { qDebug()<<"setEditorData"; QString text =index.model()->data(index,Qt::DisplayRole).toString(); if(type == "sex") { QComboBox *cmb = static_cast(editor); cmb->setCurrentText(text); } else { QTextEdit *textedit = static_cast(editor); textedit->setText(text); } }//设置model数据 void tabviewDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { qDebug()<<"setModelData"; QString text; if(type == "sex") { QComboBox *cmb = static_cast(editor); text= cmb->currentText(); } else { QTextEdit *edit = static_cast(editor); text= edit->toPlainText(); } model->setData(index,text); }void tabviewDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { qDebug()<<"updateEditorGeometry"; editor->setGeometry(option.rect); }

MainWindow.cpp
#include MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { tabviewDelegate *textedit = new tabviewDelegate(this); textedit->type = "hobby"; ui->tableView->setItemDelegateForColumn(5,textedit); //第五列,0开始计数tabviewDelegate *cmb = new tabviewDelegate(this); cmb->type = "sex"; ui->tableView->setItemDelegateForColumn(2,cmb); }

还有一些话要说 如果想要实现tableview的某列不可修改,也可以使用内置控件来实现,在createEditor函数中,改成
if(type == "sex") { QComboBox *editor = new QComboBox(parent); editor->addItem(tr("男")); editor->addItem(tr("女")); editor->setEnabled(false); //不可修改 return editor; }

【QT tableview内置控件】QT tableview内置控件
文章图片

其他的类似设置输入长度等操作,只需要在createEditor中进行相应修改即可

    推荐阅读