问题
I'm using a custom delegate to display QDoubleSpinBoxes in a QTableView. Those spinboxes display their contents with two decimals.
My problem is that I would like the QTableView to also display those numbers with two decimals while they are not being edited (at which point they are not in a QDoubleSpinBox). Or, rather, I would like to be able to specifiy a format for the QTableView's contents.
I tried to subclass QStyledItemDelegate to override displayText, but for a strange reason it crashes. It works correctly if I simply subclass QItemDelegate.
I'm using Qt 4.6.3, on Windows.
回答1:
I'm not really sure what to make of the exception you are getting. Here is a simple QStyledItemDelegate that we are using without problems. Perhaps there is something different?
#include "model_view/color_combo_delegate.h"
#include <QTimer>
#include "map_elements/common/color_combo_box.h"
ColorComboDelegate::ColorComboDelegate(QObject *parent)
: QStyledItemDelegate(parent) {
}
QWidget *ColorComboDelegate::createEditor(
QWidget *parent,
const QStyleOptionViewItem & /*option*/,
const QModelIndex & /*index*/) const {
ColorComboBox *color_combo_box = new ColorComboBox(parent);
connect(color_combo_box, SIGNAL(currentIndexChanged(int)),
this, SLOT(IndexChanged()));
QTimer::singleShot(0, color_combo_box, SLOT(Popup()));
return color_combo_box;
}
QString ColorComboDelegate::displayText(const QVariant &value,
const QLocale &/*locale*/) const {
Map::Color color = static_cast<Map::Color>(value.toInt());
return Map::color_name(color);
}
void ColorComboDelegate::IndexChanged() {
ColorComboBox *color_combo_box = qobject_cast<ColorComboBox *>(sender());
emit commitData(color_combo_box);
emit closeEditor(color_combo_box);
}
void ColorComboDelegate::setEditorData(QWidget * editor,
const QModelIndex & index) const {
ColorComboBox *color_combo_box = qobject_cast<ColorComboBox *>(editor);
Map::Color color = static_cast<Map::Color>(index.data().toInt());
color_combo_box->set_color(color);
}
void ColorComboDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const {
ColorComboBox *color_combo_box = qobject_cast<ColorComboBox *>(editor);
model->setData(index, color_combo_box->color());
}
回答2:
Well, I don't know what happened, but now it no longer crashes. And it now works.
For the record, this is my displayText method:
QString sqxSpinBoxDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
return locale.toString(value.toDouble(), 'f', Decimals);
}
来源:https://stackoverflow.com/questions/3787119/formatting-data-in-a-qtableview