在 C++ 应用程序中,有一个 QTableWidget 表,其中一些列与 QDoubleSpinBoxDelegate 相关联,但增量值通过 QComboBoxDelegate 设置在另一列的同一行上。问题是 - 在 QDoubleSpinBoxDelegate 中编辑单元格时如何设置步长值。代表本人:
#ifndef DOUBLESPINBOXDELEGATE_H
#define DOUBLESPINBOXDELEGATE_H
#include <QObject>
#include <QItemDelegate>
#include <QDoubleSpinBox>
class DoubleSpinBoxDelegate : public QItemDelegate
{
Q_OBJECT
double minVal;
double maxVal;
double oneStep;
QString suffix;
public:
DoubleSpinBoxDelegate(QObject *parent = nullptr);
DoubleSpinBoxDelegate(QObject *parent, double min, double max, double step = 0.0001, QString suffix = "");
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setEditorData(QWidget *editor, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setStepSize(double step);
};
#endif // DOUBLESPINBOXDELEGATE_H
执行:
#include "doublespinboxdelegate.h"
DoubleSpinBoxDelegate::DoubleSpinBoxDelegate(QObject *parent)
{
minVal = 1.5;
maxVal = 29.9999;
}
DoubleSpinBoxDelegate::DoubleSpinBoxDelegate(QObject *parent, double min, double max, double step, QString suffix)
{
if (parent)
{
minVal = min;
maxVal = max;
oneStep = step;
this->suffix = suffix;
}
}
QWidget *DoubleSpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QDoubleSpinBox *editor = new QDoubleSpinBox (parent);
editor->setSuffix(tr(" MHz"));
editor->setDecimals (6);
editor->setMinimum(minVal);
editor->setMaximum(maxVal);
editor->setSingleStep(oneStep);
return (QWidget *) editor;
}
void DoubleSpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
double value = index.model()->data(index, Qt::EditRole).toDouble();
QDoubleSpinBox *dSpinBox = static_cast<QDoubleSpinBox*>(editor);
dSpinBox->setValue(value);
}
void DoubleSpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QDoubleSpinBox *dSpinBox = static_cast<QDoubleSpinBox*>(editor);
dSpinBox->interpretText();
double value = dSpinBox->value();
model->setData(index, value, Qt::EditRole);
}
void DoubleSpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
很明显,在createEditor方法中,需要设置oneStep的值,但是如何从同一行的表的另一列中读取呢?
如果您的编辑器设置取决于数据,那么最好在
setEditorData. 所以对我来说更有意义。如何最正确地做到这一点取决于项目,我将列出以下选项:让我提醒您,您自己的数据角色的代码必须大于 的值
Qt::UserRole。