QT 4.5.2,QTableView不可编辑

时间:2015-06-05 16:05:41

标签: c++ qt qt-creator

我只需在表单中添加一个新的QTableView,设置模型并进行配置,但我无法编辑单元格。在其他表中,编辑没有问题。我怎么了?代码:

void MethodicWorkWidget::setupMethod3Model() {
    method3Model = new ExtSqlModel(this);
    method3Model->setTable("methodworks3");
    method3Model->setEditStrategy(QSqlTableModel::OnFieldChange);

    int typeInd = method3Model->fieldIndex("typeid");
    method3Model->setRelation(typeInd, QSqlRelation("methodworks3types", "id", "Name"));
    method3Model->setFilter("teacherid="+QString::number(teacherID));//+" AND YearID="+QString::number(yearID));

    method3Model->setHeaderData(typeInd, Qt::Horizontal, tr("Вид"));
    method3Model->setHeaderData(method3Model->fieldIndex("discipline"), Qt::Horizontal, tr("Дисциплина"));
    method3Model->setHeaderData(method3Model->fieldIndex("theme"),      Qt::Horizontal, tr("Тема"));
    method3Model->setHeaderData(method3Model->fieldIndex("date"),       Qt::Horizontal, tr("Дата проведения"));
    method3Model->setHeaderData(method3Model->fieldIndex("value"),      Qt::Horizontal, tr("Балл"));

    ui.label_2->setText(QString::number(teacherID));

    method3Model->setSort(0, Qt::AscendingOrder);

    //populate and check
    if (!method3Model->select()) {
            QMessageBox::critical(NULL, tr("Ошибка обращения к базе"), tr(
                            "Произошла ошибка при выборе руководства:\n")+manageModel->lastError().text());
    }

    ui.method3View->setModel(method3Model);
    ui.method3View->hideColumn(method3Model->fieldIndex("id"));
    ui.method3View->hideColumn(method3Model->fieldIndex("teacherid"));
    ui.method3View->setItemDelegateForColumn(typeInd, new QSqlRelationalDelegate(ui.method3View));
    ui.method3View->resizeColumnsToContents();

    connect(ui.method3AddButton, SIGNAL(clicked()), this, SLOT(method3Add()));
    connect(ui.method3DelButton, SIGNAL(clicked()), this, SLOT(method3Del()));
    ui.method3DelButton->setEnabled(method3Model->rowCount()!=0);

    if(UserInfo::role() == UserInfo::Guest){
            ui.method3AddButton->setEnabled(false);
            ui.method3DelButton->setEnabled(false);
            ui.method3View->setEditTriggers(QAbstractItemView::NoEditTriggers);
    }

}

1 个答案:

答案 0 :(得分:1)

如果QAbstractItemModel::flags结果包含Qt::ItemIsEditable标记,则可以编辑某个索引。 QSqlRelationalTableModel默认情况下是可编辑的,但您覆盖flags()并在条件!index.column() < realColNum-2不满足时禁用编辑。看来你在这种情况下有错误。请注意,!运算符的优先级高于<。你可能想要index.column() >= realColNum-2。另请检查realColNum值。