PDA

View Full Version : How to add one empty row in ComboBox with model



TomASS
3rd August 2009, 13:27
Hi again :)

I've a ComboBox fill by QSqlQueryModel:


ComboKierowcy = new QComboBox(parent);
QSqlQueryModel *ComboKierowcyModel = new QSqlQueryModel();

ComboKierowcyModel->setQuery( "SELECT * FROM kierowcy ORDER BY Nazwisko" );
if (ComboKierowcyModel->lastError().isValid())
qDebug() << ComboKierowcyModel->lastError();

QModelIndex tmp;
ComboKierowcy->setModel(ComboKierowcyModel);
ComboKierowcy->setModelColumn(1);

Everything is ok, but I need a one empty position on the first place. How add this?

victor.fernandez
3rd August 2009, 14:03
You will have to subclass QSqlQueryModel and reimplement data() and rowCount() and perhaps some more methods. You can do something like this:

In myquerymodel.h file:


#include <QSqlQueryModel>

class MyQueryModel : public QSqlQueryModel
{
Q_OBJECT

public:
MyQueryModel(QObject *parent = 0);

virtual QVariant data(const QModelIndex& item, int role = Qt::DisplayRole) const;
virtual int rowCount(const QModelIndex& parent = QModelIndex()) const;
};


In the myquerymodel.cpp file:


MyQueryModel::MyQueryModel(QObject *parent) : QSqlQueryModel(parent)
{
}

QVariant MyQueryModel::data(const QModelIndex& item, int role) const
{
if(item.row() == 0)
return QVariant();

QModelIndex fakeItem = this->QSqlQueryModel::index(item.row()-1, item.column());
return this->QSqlQueryModel::data(fakeItem, role);
}

int MyQueryModel::rowCount(const QModelIndex& parent) const
{
return this->QSqlQueryModel::rowCount(parent) + 1;
}