本文主要是介绍QTableWidget使用自定义代理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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);
这篇关于QTableWidget使用自定义代理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!