我正在使用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。
答案 0 :(得分: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"));
由于你如何制作表格,我对你如何真正希望它应用于你的项目感到困惑。也许如果你可以描述你的计划是什么,那么我可以提供更多帮助。