QTableView的单元格为空,但标题显示

时间:2013-03-21 00:19:28

标签: qt delegates qtableview

我创建了一个几乎从Qt的Spin Box Delegate示例复制的委托,我正在尝试填充QTableView。但是,我遇到一个奇怪的问题,表头显示但是单元格是空的,无法点击。

Problem with QTableView and delegate

代表代码:

#include "double_spinbox_delegate.h"

DoubleSpinBoxDelegate::DoubleSpinBoxDelegate(QObject *parent) : QItemDelegate(parent){}

QWidget *DoubleSpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const{
    QDoubleSpinBox *editor = new QDoubleSpinBox(parent);
    editor->setValue(0);

//    if (index.column() == 0){
//        editor->setMinimum(0);
//        editor->setMaximum(255);
//    }
//    else{
//        editor->setMinimum(0);
//        editor->setMaximum(1);
//    }

    return editor;
}

void DoubleSpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const{
    double value = index.model()->data(index, Qt::EditRole).toDouble();

    QDoubleSpinBox *doubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
    doubleSpinBox->setValue(value);
}

void DoubleSpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{
    QDoubleSpinBox *doubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
    doubleSpinBox->interpretText();
    double value = doubleSpinBox->value();

    model->setData(index, value, Qt::EditRole);
}

void DoubleSpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const{
    editor->setGeometry(option.rect);
}

和我在表单构造函数中调用的函数

void MainWindow::InitializeColorTable(){
    QTableView *tableColor = ui->tableColor;

    QStandardItemModel *model = new QStandardItemModel(4, 4, ui->tableColor);
    // QStandardItemModel *model = this->colorTableModel;
    tableColor->setModel(model);

    DoubleSpinBoxDelegate delegate;
    tableColor->setItemDelegate(&delegate);

    model->setHorizontalHeaderLabels(QStringList() << tr("Value") << tr("R") << tr("G") << tr("B"));

    for (int row = 0; row < model->rowCount(); ++row){
        for (int col = 0; col < model->columnCount(); ++col){
            QModelIndex index = model->index(row, col, QModelIndex());
            model->setData(index, QVariant((row + 1.0) * (col + 1.0)), Qt::EditRole);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您的委托在堆栈上分配,并在超出范围后被删除。

DoubleSpinBoxDelegate delegate;
tableColor->setItemDelegate(&delegate);

使用new创建代理。