0

Qt version: 5.8

Let's say I have the following 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

Let's say I want to populate the following Table View or Table Widget with a mixture of that data like so

// 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

What is the best/recommended way to do this? I can see the following two ways, but I feel neither are the best way to do this

  1. Use a Table Widget, which is an item-based table view with a default model. To do this, I'm guessing I would need to make QSqlQuerys to get the data from my QSqlDatabase and just populate the Table Widget that way.
  2. Use a Table View, which would require me to create my own QSqlTableModel for the data model of the view. According to the documentation for QSqlTableModel, it is a high-level interface for reading and writing database records from a single table. This means I would need two QSqlTableModels, one for each of my tables above. However, the Table View can only use one model, and it will show all the data from that model. I think the only way this would work is to combine the tables into one table with only the information I want the user to see. I feel like that would be very ugly but possible. In that case, should I have three tables total - the two above plus the combined one for the users to see?

I feel like #1 is the better of those two, but I'm wondering if there's still a better way than both of those.

Programmer_D
  • 601
  • 2
  • 15
  • 27
  • Possible duplicate of [How to display content of multiple QSqlTableModels in one QTableView?](http://stackoverflow.com/questions/17156286/how-to-display-content-of-multiple-qsqltablemodels-in-one-qtableview) – MrEricSir May 15 '17 at 03:14

1 Answers1

0

If person_id is primary key of table people you can use QtSql.QsqlRelationalTableModel to show data from several tables in an QtWidgets.QTableView, here your example:

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);
a_manthey_67
  • 4,046
  • 1
  • 17
  • 28