PDA

View Full Version : Adding extra column for QTableView while having QSqlTableModel



Sekkkyyy
14th August 2015, 07:37
here is what i want to appear on my QTableView


---col1 col2 cus1
r1
r2
r3
..

cus1 will be my custom column and i want to put some text or notes on it. col1 and col2 are columns from the database and it will be automatically populated. I have a fully working QTableView with a QSqlTableModel.

Ive been reading on how to add virtual columns they say that it can be done by using QProxyModel.I checked the documentation and found out that it's "obsolete".

What alternatives do i have and where should i start?

anda_skoa
14th August 2015, 09:20
You have two options:

- use a proxy model (and no, the proxy model approach is not obsolete)
- derive from the sql model class, override columnCount(), data() and headerData()

Cheers,
_

Sekkkyyy
14th August 2015, 09:45
edit: oh nvm i made it work somehow. weird though because i don't see columnCount.

I just override the columnCount and i set the headerdata.

Now i need to know how to set its data.

wysota
14th August 2015, 10:02
By reimplementing setData() and storing the data somewhere.

Sekkkyyy
14th August 2015, 10:12
Hello!

Here is what i have so far:




class Manifest : public QSqlTableModel
{
public:
Manifest(QObject * parent = 0, QSqlDatabase db = QSqlDatabase() ):
QSqlTableModel(parent, db){

}

Qt::ItemFlags flags ( const QModelIndex & index ) const
{
if (index.column() == 1 || index.column() == 2)
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
else
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}


int columnCount(const QModelIndex &/*parent*/) const
{
return 3;
}


QVariant data(const QModelIndex &index, int role) const
{



return QSqlTableModel::data(index, role);
}

};



This is my WIP.
I reimplemented flags so that only certain indexes can be edited.
I am currently trying to override the "data", because i want to put a checkbox on it.

Are there any sites wherein can i see the implementations? It's kinda hard if i can't see the underlying implementations.

anda_skoa
14th August 2015, 11:23
http://code.woboq.org/qt5/

Since you want to add a column, you columnCount() would probably first get the value from the base class and then add 1



int Manifest::columnCount(const QModelIndex &parent)
{
return QSqlQueryModel::columnCount(parent) + 1;
}

In data() you would then check if index.column() is your column and if not, delegate to base class as-is.

Cheers,
_