PDA

View Full Version : Custom Model? Custom View? Custom Delegate?



Doug Broadwell
9th February 2010, 17:34
I currently have a QSqlTableModel and a QTableView. One of the column's data represents US Dollar amounts. I would like to format it in US style: $n,nnn.nn and have it editable. It's confusing to me what I need to do to implement this; my best guess is a custom delegate (??). Since this kind of formatting must be very common, someone must have already created a delegate to do this - possibly by passing a formatting string to the delegate. Does anyone know if such a thing exists? If not, please point me in the direction to proceed.

Thanks!

franz
9th February 2010, 21:47
Indeed, go for the delegate.

Doug Broadwell
9th February 2010, 22:14
Thanks very much!

Doug Broadwell
10th February 2010, 18:34
Still confused. Do I subclass QAbstractItemDelegtate, QItemDelegate, or QStyleItemDelegate? Looking at the sources, it looks very complex.

Thanks

Doug Broadwell
11th February 2010, 20:23
Here is how I solved my problem; I subclassed QStyledItemDeleage and altered initStyleOption and displayText:

void MoneyDelegate::initStyleOption(QStyleOptionViewIte m *option, const QModelIndex &index) const
{
QStyledItemDelegate::initStyleOption(option, index); // Let base handle all else.
option->displayAlignment = Qt::AlignRight | Qt::AlignCenter; // Force Right Alignment
}

QString MoneyDelegate::displayText(const QVariant &value, const QLocale& locale) const
{
if(value.userType() == QMetaType::Float || value.userType() == QVariant::Double)
{
QString text = "$" + QString().setNum(value.toDouble(), 'f', 2);
return text;
}
return QStyledItemDelegate::displayText(value, locale); // Not a Double so have base function deal with it.
}

Now ... to figure out the Editor ...