当前位置: 代码迷 >> QT开发 >> 怎么用QTableView修改数据库内容
  详细解决方案

怎么用QTableView修改数据库内容

热度:74   发布时间:2016-04-25 04:29:26.0
求助:如何用QTableView修改数据库内容?
各位,我通过tableView->setModel(model)已经可以看到数据库中的内容,如何在tableview中直接修改里面的内容然后更新数据库呢?

model的设置是
model->setEditStrategy(QSqlTableModel::OnManualSubmit);


在网上查都说执行下面的代码即可
  model->database().transaction();
  model->submitAll()) 
  model->database().commit(); 

为什么我在tableview中修改后执行上述语句,数据库内容还是不更新呢?
model设置编辑策略改成另外两个模式同样不行。

是tableview初始化时需要进行哪些设置吗?

分不多,请各位帮帮忙,谢谢

------解决方案--------------------
这个需要重写一些model的方法

当然你需要编辑也要实现自己的delegate

class MyTableDelgate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit MyTableDelgate(QObject *parent = 0);

protected:
//basic function for a read-only delegate, you can draw anything with the painter
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;

//edit 5 function
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;

private:
QLineEdit * m_LineEdit;
};



model

class MyTableDelgate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit MyTableDelgate(QObject *parent = 0);

protected:
//basic function for a read-only delegate, you can draw anything with the painter
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;

//edit 5 function
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;

};

很简单。你懂的。