1 根据数据内容设定宽
resizeColumnToContents, resizeColumnsToContents
2 去掉网格 setShowGrid
3 委托
需要在单元格里进行特别处理,如需要QLineEdit, QComcoBox等时,需要用委托机制来实现。
委托需要实现的几个函数
QTableView, QTableWidget对其数据进行委托:setItemDelegate, setItemDelegateForColumn, setItemDelegateForRow
委托时QItemDelegate需要重新实现的函数:createEditor(创建控件),setEditorData(设置值),setModelData,updateEditorGeometry(设置大小)
部分实现代码示例
QWidget *LLineEditDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QLineEdit *editor = new CompleteLineEdit(parent);
return editor;
}
void LLineEditDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString value = index.model()->data(index, Qt::EditRole).toString();
QLineEdit *lineEdit = static_cast<QLineEdit *>(editor);
lineEdit->setText(value);
}
void LLineEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QLineEdit *lineEdit = static_cast<QLineEdit *>(editor);
QString value = lineEdit->text();
model->setData(index, value, Qt::EditRole);
}
void LLineEditDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}