更改后的QSqlRelationalModel模型/视图更新

时间:2014-01-05 19:19:04

标签: qt qtableview qtsql qsqltablemodel

我在更改后更新模型/视图时出现问题。

为了更好地解释我的意思,我用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;
};

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

添加新行后出现同样的问题。

1 个答案:

答案 0 :(得分:2)

尝试添加model-&gt; setEditStrategy(QSqlTableModel :: OnManualSubmit)