4

我在更改后更新模型/视图时遇到问题。

为了更好地解释我的意思,我用 SQLite 写了一个简单的例子。

所以 main.cpp 文件:

#include <QApplication>

#include "MainForm.h"

void createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("deptemployee.dat");
    if (!db.open()) {
        QMessageBox::information(0, QObject::tr("Database Error"), db.lastError().text());
        db.close();
        return;
    }
}

void createFakeData()
{
    QSqlQuery query;
    query.exec("DROP TABLE Department");
    query.exec("DROP TABLE Employee");

    query.exec("CREATE TABLE Department(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(40) NOT NULL)");
    query.exec("CREATE TABLE Employee(id INTEGER PRIMARY KEY AUTOINCREMENT, departmentid INTEGER NOT NULL, FOREIGN KEY (departmentid) REFERENCES Department)");

    query.exec("INSERT INTO Department(name) VALUES('SomeDepartment')");
    query.exec("INSERT INTO Department(name) VALUES('AnotherDepartment')");

    query.exec("INSERT INTO Employee(departmentid) VALUES(1)");
    query.exec("INSERT INTO Employee(departmentid) VALUES(2)");
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    createConnection();
    createFakeData();

    MainForm form;
    form.resize(500, 600);
    form.show();

    return a.exec();
}

MainForm.h 文件:

#pragma once

#include <QWidget>
#include <QObject>

#include <QtWidgets>
#include <QtSql>

enum {
    Employee_Id = 0,
    Employee_DepartmentId = 1
};

class MainForm : public QWidget
{
    Q_OBJECT

public:
    MainForm()
    {
        model = new QSqlRelationalTableModel(this);
        model->setTable("Employee");
        model->setRelation(Employee_DepartmentId, QSqlRelation("Department", "id", "name"));
        model->select();

        view = new QTableView;
        view->setModel(model);
        view->setItemDelegate(new QSqlRelationalDelegate(this));

        addButton = new QPushButton("Add");
        connect(addButton, SIGNAL(clicked()), SLOT(addButtonClicked()));

        QVBoxLayout* mainLayout = new QVBoxLayout;
        mainLayout->addWidget(view);
        mainLayout->addWidget(addButton);
        setLayout(mainLayout);

        model->select();
    }

private slots:
    void addButtonClicked()
    {
        int row = model->rowCount();
        model->insertRow(row);
        QModelIndex index = model->index(row, Employee_DepartmentId);
        view->setCurrentIndex(index);
        view->edit(index);
    }

private:
    QPushButton*                addButton;
    QTableView*                 view;
    QSqlRelationalTableModel*   model;
};

那么关于错误......在编辑包含外键的单元格后,显示的值变得错误。因此,例如在部门更改后,它显示为整数而不是字符串。为什么?是Qt错误吗?

添加新行后同样的问题。

4

1 回答 1

2

尝试添加模型->setEditStrategy(QSqlTableModel::OnManualSubmit)

于 2014-04-03T06:08:04.183 回答