Formatting data in a QTableView

泪湿孤枕 提交于 2019-12-08 06:58:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!