2

我正在使用 QSqlRelationalModel,但我遇到了一些问题。

例如,如果我们处理简单的表格,例如:

Location
+------+--------+
|  id  |  name  |
+------+--------+

Department
+------+-------------+
|  id  | location_id |
+------+-------------+

然后我可以写:

departmentModel = new QSqlRelationalTableModel(this);
departmentModel->setTable("Department");
departmentModel->setRelation(Department_LocationId, QSqlRelation("Location", "id", "name"));
departmentView = new QTableView;
departmentView->setModel(departmentModel);
departmentView->setItemDelegate(new QSqlRelationalDelegate(this));

它会正常工作,并显示位置名称而不是 ID。

但就我而言,我不能应用这种方法。假设我有下一张桌子:

Person
+------+-------------+
|  id  |  firstname  |
+------+-------------+

Experience
+------+------------------+
|  id  |  person_id (FK)  |
+------+------------------+

Participant
+------+-----------------+
|  id  |  experience_id  |
+------+-----------------+ 

假设我想使用 Participant 作为 QSqlRelationalTable:

QSqlRelationalTable participantModel;
participantModel->setTable(Participant);
...
participantView->setModel(participantModel);
participantView->setItemDelegate(new QSqlRelationalDelegate(this));

而且我想在视图中显示 Person.firstname 而不是 experience_id (而且我不想失去编辑功能)。我怎样才能做到这一点?

我不能像上面的例子那样使用 setRelation() ,因为:

participantModel->setRelation("experience_id", QSqlRelation("Experience", "id", WHAT_DO_I_HAVE_TO_WRITE_HERE_TO_GET_WHAT_I_WANT);

我不能写“person_id”,因为我想显示名字而不是 person_id。

4

1 回答 1

0

我认为您应该将表格重新设计成这样

Participant
+------+------------------+----------------------+
|  id  |  person_id (FK)  |  experience_id (FK)  |
+------+------------------+----------------------+ 

Person
+------+-------------+
|  id  |  firstname  |
+------+-------------+

Experience
+------+--------------+--------
|  id  |  experience  |  year   . . . (and so on)
+------+--------------+-------------

现在您可以:

departmentMode->setTable("Participant");
departmentModel->setRelation(1,QSqlRelation("Person","id","firstName"));
departmentModel->setRelation(2,QSqlRelation("Experience","id","experience"));

由于您制作表格的方式,我对您真正希望如何将其应用于您的项目感到非常困惑。也许如果你能描述你的计划是什么,我可以提供更多帮助。

于 2016-02-03T14:12:47.997 回答