Qt C++ - 在一个视图中显示来自多个 SQLite 表的数据
Qt C++ - Displaying data in one view from multiple SQLite tables
Qt版本:5.8
假设我有以下 SQL tables
-- People
person_id | first_name | last_name | age
-- Cars, person_id is a foreign key to show that this person owns this car
car_id | car_year | car_make | car_model | person_id
假设我想填充以下 Table View 或 Table Widget这样的数据
// Table that the user sees. Notice that not all the information from the tables is shown.
first_name | last_name | car_year | car_make | car_model
best/recommended 的方法是什么?我可以看到以下两种方式,但我觉得这两种方式都不是最好的方式
- 使用 Table 小部件,这是一个基于项目的 table 视图,带有默认模型。为此,我猜我需要制作 QSqlQuerys 以从我的 QSqlDatabase 获取数据并填充 Table 这样的小部件。
- 使用 Table 视图,这需要我创建自己的 QSqlTableModel视图的数据模型。根据 QSqlTableModel 的文档,它是从 single table 读取和写入数据库记录的高级接口。这意味着我需要两个 QSqlTableModels,一个对应上面的每个 tables。但是,Table 视图只能使用一个模型,并且它将显示该模型的所有数据。我认为唯一可行的方法是将 table 组合成一个 table,其中仅包含我希望用户看到的信息。我觉得那会很丑陋但有可能。在那种情况下,我是否应该总共设置三个 table - 上面两个加上合并后的一个供用户查看?
我觉得 #1 是这两个中更好的一个,但我想知道是否还有比这两个更好的方法。
如果 person_id
是 table people
的主键,您可以使用 QtSql.QsqlRelationalTableModel
在 [=14= 中显示来自多个 table 的数据],这里是你的例子:
QSqlRelationalTableModel rm = new QSqlRelationalTableModel(parentObject, database);
rm→setTable(„cars“);
rm→setRelation(4, QSqlRelation(„people“, „person_id“, „first_name, last_name“);
rm→select();
QTableView tv = new QTableView();
tv→setModel(rm);
tv→hideColumn(0); # hide column car_id
hh = tv->horizontalHeader();
hh→moveSection(4, 0); # change order of columns
hh→moveSection(5, 1);
Qt版本:5.8
假设我有以下 SQL tables
-- People
person_id | first_name | last_name | age
-- Cars, person_id is a foreign key to show that this person owns this car
car_id | car_year | car_make | car_model | person_id
假设我想填充以下 Table View 或 Table Widget这样的数据
// Table that the user sees. Notice that not all the information from the tables is shown.
first_name | last_name | car_year | car_make | car_model
best/recommended 的方法是什么?我可以看到以下两种方式,但我觉得这两种方式都不是最好的方式
- 使用 Table 小部件,这是一个基于项目的 table 视图,带有默认模型。为此,我猜我需要制作 QSqlQuerys 以从我的 QSqlDatabase 获取数据并填充 Table 这样的小部件。
- 使用 Table 视图,这需要我创建自己的 QSqlTableModel视图的数据模型。根据 QSqlTableModel 的文档,它是从 single table 读取和写入数据库记录的高级接口。这意味着我需要两个 QSqlTableModels,一个对应上面的每个 tables。但是,Table 视图只能使用一个模型,并且它将显示该模型的所有数据。我认为唯一可行的方法是将 table 组合成一个 table,其中仅包含我希望用户看到的信息。我觉得那会很丑陋但有可能。在那种情况下,我是否应该总共设置三个 table - 上面两个加上合并后的一个供用户查看?
我觉得 #1 是这两个中更好的一个,但我想知道是否还有比这两个更好的方法。
如果 person_id
是 table people
的主键,您可以使用 QtSql.QsqlRelationalTableModel
在 [=14= 中显示来自多个 table 的数据],这里是你的例子:
QSqlRelationalTableModel rm = new QSqlRelationalTableModel(parentObject, database);
rm→setTable(„cars“);
rm→setRelation(4, QSqlRelation(„people“, „person_id“, „first_name, last_name“);
rm→select();
QTableView tv = new QTableView();
tv→setModel(rm);
tv→hideColumn(0); # hide column car_id
hh = tv->horizontalHeader();
hh→moveSection(4, 0); # change order of columns
hh→moveSection(5, 1);