PDA

View Full Version : QTableView and SqlLite



Myrgy
4th October 2009, 14:33
I use SQLite 3.
in that database I have table


CREATE TABLE [languages] (
id INTEGER PRIMARY KEY AUTOINCREMENT,
language TEXT NOT NULL ,
used BOOL NOT NULL
);


I create new model and set that options


m_langugesTableModel = new QSqlTableModel(NULL, database);
m_langugesTableModel->setTable("languages");
m_langugesTableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

res = m_langugesTableModel->select();
res = m_langugesTableModel->removeColumn(0);
res = m_langugesTableModel->setHeaderData(0, Qt::Horizontal, QObject::tr("Language"));
res = m_langugesTableModel->setHeaderData(1, Qt::Horizontal, QObject::tr("Enabled"));



than I create new QTableView and set model for that view.


tv_languages->setModel(m_languagesTableModel);


I want to edit used field of database using QCheckBox, but if I create Delegate, than I don't now how create correct paint method for that delegate.
If I create my own model, than CheckBox draw in one place, but to edit value I had to twice click near checkbox.

I try use delegate and fags() method of my model, but than I got two checkboxes, when edit value.

How can I get CheckBox in table view, than edit with one click?

Please, help me to solve my problem.

Myrgy
4th October 2009, 15:54
Now I make model, that correctly show data from databse, but if I remove ID collumn from model, than I get QSqlQuery::value: not positioned on a valid record.


Model for table.


class LangableModel:public QSqlTableModel
{
int colWithCheckBox;
public:
LangableModel(QSqlDatabase db)
:QSqlTableModel(NULL,db)
{
colWithCheckBox = 1;
}

Qt::ItemFlags flags( const QModelIndex &index) const
{
Qt::ItemFlags flags = QSqlTableModel::flags(index);
if (index.column() == colWithCheckBox)
{
return Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsU serCheckable;
}
return flags;
}
QVariant data ( const QModelIndex & index, int role ) const
{
QVariant value = QSqlTableModel::data(index, role);
if (index.column() == colWithCheckBox)
{
if(role == Qt::CheckStateRole)
return (QSqlTableModel::data(index).toInt() != 0) ? Qt::Checked : Qt::Unchecked;
else
return QVariant();
}
return value;
}

bool setData ( const QModelIndex & index, const QVariant & value, int role = Qt::EditRole )
{
if (index.column() == colWithCheckBox)
{
QString val = (value==Qt::Checked)?"1":"0";
switch( role )
{
case Qt::CheckStateRole:
qDebug()<<"val:"<<val<<" index:"<<index;
return QSqlTableModel::setData(index, val, Qt::EditRole);
default:
return false;
}
}else
return QSqlTableModel::setData(index, value, role);
}
};