PDA

View Full Version : QSqlQueryModel and QTableView, with a custom ItemDelegate



SIFE
25th February 2013, 02:00
I have QTableView connected with QSqlQueryModel, the first column I inserted it after populating data from database. The first column will be checkbox, checked is the second column have a matched value from a QStringList variable I pass to the delegate. My problem is the delegate never draws QCheckBox on the first column.
Here is how I set the delegate:


QString sqlQuery;
sqlQuery = "SELECT ProCode, ProName, ProPrice FROM Promotions";

QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery(sqlQuery);
model->insertColumns(0, 1);

ui->promotionsList->setModel(model);

QStringList promotions = this->workerMod->promotionsList->text().split(',');

PromotionDelegate *checkDelegatePromos = new PromotionDelegate(this);
checkDelegatePromos->setPromotions(promotions);
ui->promotionsList->setItemDelegate(checkDelegatePromos);

The delegate I implement:


QWidget *PromotionDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(index.isValid() && index.column() == 0)
{
//QMessageBox::critical(0, QString::number(index.row()), "1"); Also, this message never fired up!
QCheckBox *check = new QCheckBox(parent);
check->setCheckState(Qt::Unchecked);
return check;
}
else
return QItemDelegate::createEditor(parent, option, index);
}

void PromotionDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if(index.isValid() && index.column() == 0)
{
QCheckBox *check = static_cast<QCheckBox *>(editor);
QModelIndex inx = index.model()->index(index.row(), 1);
QString prom = index.model()->data(inx, 0).toString();
for(int i = 0; i< this->m_promotions.length(); ++i)
{
if(this->m_promotions.at(i) == prom)
{
check->setCheckState(Qt::Checked);
break;
}
}
}
else
QItemDelegate::setEditorData(editor, index);
}

void PromotionDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{

}

void PromotionDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(index.isValid() && index.column() == 0)
{
editor->setGeometry(option.rect);
}
else
QItemDelegate::updateEditorGeometry(editor, option, index);
}

void PromotionDelegate::setPromotions(QStringList &promotions)
{
this->m_promotions = promotions;
}