QTableWidget表格使用自定义代理,以QLineEdit为例
继承QItemDelegate类
主要重写四个方法
createEditor()
setEditorData()
setModelData()
updateEditorGeometry()
#include <QItemDelegate>
#include <QLineEdit>
class TableItemEditDelegate : public QItemDelegate
{
Q_OBJECT
public :
TableItemEditDelegate(QObject *parent = nullptr) : QItemDelegate(parent){}
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(option);
Q_UNUSED(index);
QLineEdit *editor = new QLineEdit(parent);
editor->setValidator(new QRegExpValidator(QRegExp("^[0-9]{1,6}$")));
return editor;
}
void setEditorData(QWidget *editor, const QModelIndex &index) const
{
QLineEdit *control = dynamic_cast<QLineEdit*>(editor);
control->setText(index.model()->data(index, Qt::EditRole).toString());
}
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QLineEdit *control = dynamic_cast<QLineEdit*>(editor);
model->setData(index, control->text(), Qt::EditRole);
}
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(index);
editor->setGeometry(option.rect);
}
};
调用
TableItemEditDelegate *comboBoxDelegate = new TableItemEditDelegate;
this->ui->tableWidget->setItemDelegateForColumn(1, comboBoxDelegate);