List data from two table in tableView - c++

How can I list data from two table in tableView?
Database (Example) Sqlite:
tb_sales
tb_product
tb_value
tb_customer_id (Customer Id "tb_customer")
tb_customer
tb_customer_id (id primary key)
tb_name
tb_state
With QSqlRelationalTableModel fetch only the client's name. Also need the state.
model= new QSqlRelationalTableModel(this);
model->setTable("tb_sales");
model->setRelation(2, QSqlRelation("tb_customer", "tb_customer_id", "tb_name"));
model->select();
ui->tableView->setModel(model);

QSqlRelationalTableModel only allows you to include one column from the secondary table. You can use QSqlQueryModel to have a query in which you join the two tables :
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT tb_sales.* , tb_customer.tb_name, tb_customer.tb_state FROM tb_sales LEFT JOIN tb_customer ON tb_sales.tb_customer_id = tb_customer.tb_customer_id");
ui->tableView->setModel(model);

Related

Filtering QSqlRelation in QSqlRelationalTableModel

I have two tables like:
Person (Id, Name, JobID, Age)
Jobs (Id, Company, Salary)
I'm using a SqlRelationalTableModel and it's working with the following QSqlRelation:
model-> setTable("Person")
model-> setRelation(2,QSqlRelation("Jobs", "Id", "Company"))
My problem is that now I want to show only the jobs with salaries over 50000 and I don't know how to filter Jobs table to do it since setFilter only affects Person table.
You can use QSqlQueryModel
QSqlQueryModel* model = new QSqlQueryModel();
model->setQuery("select * from Person left join Jobs on Person.JobID=Jobs.Id where Salary>50000");

How to get one record from sqlite and display in tableview

What I want to do is take the input from a text field (i.e cust_name), match and fetch the record from database with column cust_name.
Database has table cust and column cust_name, address. I want to find a way to display the data in tablview of QSqlTableModel.
QSqlTableModel *model = new QSqlTableModel;
model->setTable("cust");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
ui->tableView->setModel(model);
ui->tableView->setColumnHidden(0,1);
ui->tableView->setColumnHidden(5,1);
ui->list->setModel(model);
ui->list->setModelColumn(1);
model->select();
This successfully displays the whole table named cust. I want to be able to change it into displaying the single record matching the search term.
Use function index() to access custom row/column.
QSqlTableModel *model = new QSqlTableModel;
int value = model->index(row,column).data().toInt();
In your situation like this:
int value = model->index((model->rowCount()-1),column).data().toInt();
or custom sql query :
SELECT * FROM tablename ORDER BY id DESC LIMIT 1;

Get duplicated record by using QSqlTableModel

I have a table that contains duplicated records.
I used following code to put the data into a QTableView:
QSqlTableModel *dataModel = new QSqlTableModel();
dataModel->setTable("table_name");
dataModel->select();
now I wanna to query duplicated records. I use group by and having for do that in sql but I haven`t any idea to how do this in qt.
Finally I found the solution, I used "setFilter" method as bellow:
dataModel = new QSqlTableModel();
dataModel->setTable("CUSTOMER");
QString filter_txt = "id in (select id FROM CUSTOMER GROUP BY id HAVING count(*) >1)" ;
dataModel->setFilter(filter);
dataModel->select();

connect QTreeWidgetItem to database

Im working on a project where im trying to build a QTreeWidget that has multiple QTreeWidgetItems
and once i click on a particular item it connects to a database and shows a query result in a tableview model, until now every thing works fine.
the problem is that i want each item to output different resut depending on some criteria on the same table where this criteria is only changing the value of an attribute, and this value is the same of the item name. for example item named 122 and the table has atribute called no. when we click on item 122 the result of this query must be shown (select * from table where no=122)
any help :)
I am assuming you have a QTableView backed by a QSqlQueryModel or QSqlTableModel.
You can connect to the signal QTreeWidget::itemSelectionChanged() and then in the slot you get the current item with selectedItems()[0]. Then you create your query:
QSqlQuery query;
query.prepare("select * from table where no=:no");
query.bindValue(":no", number);
query.exec();
Finally you can use setQuery (const QSqlQuery & query) on the model. This should update your view.
I hope I understood correctly what you want to achieve.

Why do INSERT and DELETE screw up QTableView (Qt, C++, sqlite)?

After setting an INSERT or DELETE query on QSqlQueryModel, my QTableView becomes screwed up. For example I hid the ID column by calling view->hideColumn(ID); but after an INSERT or DELETE the ID column becomes visible.
How can I automatically reset my view to the previous settings in these cases?
I guess the problem is in QSqlQueryModel::setQuery you're eventually calling every time content gets reloaded and rows inserts\deletes. Looking at the setQuery implementation I would suggest: depending on the query your model can be reset including columns settings change which should trigger view columns update.
As Qt documentation suggests:
The QSqlQueryModel class provides a
read-only data model for SQL result
sets.
so I would use direct QSqlQuery calls for the data updates and then would reload the model with the same query. Or consider switching to QSQLTableModel, which is quite handy for single table content manipulation and supports inserts updates and deletes. See if an example below would work for you:
set up database, view and model:
QSqlTableModel *_model;
QTableView *_view;
...
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
db.open() ;
QSqlQuery query;
query.prepare("CREATE TABLE IF NOT EXISTS person (id INTEGER UNIQUE PRIMARY KEY, name VARCHAR(30))");
query.exec();
query.prepare("INSERT INTO person (name) VALUES ('test1')");
query.exec();
query.prepare("INSERT INTO person (name) VALUES ('test2')");
query.exec();
_model = new QSqlTableModel(this, db);
_model->setTable("person");
_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
_model->select();
_model->setHeaderData(1, Qt::Horizontal, tr("name"));
_model->setSort(1, Qt::AscendingOrder);
_view = new QTableView(this);
_view->setModel(_model);
_view->hideColumn(0);
add new row:
QSqlRecord record;
_model->insertRecord(-1, record);
delete selected row(s):
QModelIndexList selected = _view->selectionModel()->selectedIndexes();
for (int i = 0; i < selected.size(); ++i)
_model->removeRows(selected.at(i).row(), 1);
submit changes:
_model->submitAll();
hope this helps, regards