当你的sqlite为小数类型,你会发现默认只能有2个小数点。这时候要用代理来实现这一列的类型,使他符合我们的小数点及最大最小值等要求。首先借花献佛:
数据库操作QTableView保存小数点的位数_尘客-追梦的博客
DoubleSpinBoxDelegate::DoubleSpinBoxDelegate(QObject *parent) : QStyledItemDelegate(parent) { } QWidget* DoubleSpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (QVariant::Double == index.model()->data(index, Qt::EditRole).type()) { QDoubleSpinBox *pEditor = new QDoubleSpinBox(parent); pEditor->setFrame(false); pEditor->setMinimum(-180.0000000); pEditor->setMaximum(180.0000000); pEditor->setDecimals(7); return pEditor; } else { return QStyledItemDelegate::createEditor(parent, option, index); } } void DoubleSpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { if (QVariant::Double == index.model()->data(index, Qt::EditRole).type()) { double value = index.model()->data(index, Qt::EditRole).toDouble(); QDoubleSpinBox *pSpinBox = static_cast<QDoubleSpinBox*>(editor); pSpinBox->setValue(value); } else { QStyledItemDelegate::setEditorData(editor, index); } } void DoubleSpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (QVariant::Double == index.model()->data(index, Qt::EditRole).type()) { QDoubleSpinBox *pSpinBox = static_cast<QDoubleSpinBox*>(editor); pSpinBox->interpretText(); double value = pSpinBox->value(); model->setData(index, value, Qt::EditRole); } else { QStyledItemDelegate::setModelData(editor, model,index); } } void DoubleSpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { editor->setGeometry(option.rect); }
这时小数点就正常了,但是你会发现closeEditor信号没发射,用另一个来监听就行了:
connect(view->itemDelegateForColumn(8),&QAbstractItemDelegate::closeEditor,this,[=](){ ui->pushButton->setEnabled(true); });
这个监听适用于我们前面说的自定义委托:
如何优雅的设置qtablewidget qtableview某列不可编辑、只读?-3YL的博客 (labisart.com)