Continuing to work with tables to Qt, we would like to spent the time, how to install the filter on the model of data representation in QSqlTableModel or QSqlRelationalTableModel . Therefore, the program code of the tutorial on QSqlTableModel was taken to describe the installation of the filter as a basis for the process.
The code was written in QtCreator 3.3.1 based on Qt 5.4.1.
Project structure
In this lesson, the project structure is similar to the project of the lesson QSqlTableModel.
mainwindow.ui
Add the additional object in the main window of the application, namely, to add the following elements:
- dateEditFROM - start date;
- dateEditTO - end date;
- timeEditFROM - start time;
- timeEditTO - end time;
- pushButton - button, by pressing which the filter will be applied.
mainwindow.h
The header is added to the filter for processing SLOT button is pressed, which is added to the filter table.
#ifndef MAINWINDOW_H #define MAINWINDOW_H *** namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT *** private slots: void on_pushButton_clicked(); *** }; #endif // MAINWINDOW_H
mainwindow.cpp
This file is changed only partially, and one method is added for processing SLOT button is pressed.
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { *** } MainWindow::~MainWindow() { delete ui; } void MainWindow::setupModel(const QString &tableName, const QStringList &headers) { *** } void MainWindow::createUI() { *** ui->dateEditFROM->setDate(QDate::currentDate()); ui->dateEditTO->setDate(QDate::currentDate()); on_pushButton_clicked(); } /* The method for processing a button is pressed and part-filter model to represent tabular data * */ void MainWindow::on_pushButton_clicked() { /* Установка фильтра представляет из себя часть SQL запроса * который начинается после слова WHERE в SQL запросе. * Следовательно для специалистов, работавших с SQL не составит труда * сформировать нужный фильтр * */ model->setFilter(QString( TABLE_DATE " between '%1' and '%2' and " TABLE_TIME " between '%3' and '%4'") .arg(ui->dateEditFROM->date().toString("yyyy-MM-dd"), ui->dateEditTO->date().toString("yyyy-MM-dd"), ui->timeEditFROM->time().toString("hh:mm:ss"), ui->timeEditTO->time().toString("hh:mm:ss"))); model->select(); }
Note. To install the filter in QSqlQueryModel just need to set the appropriate filter in the SQL query that is sent to this model.
database.h and database.cpp
The data files are not made absolutely no changes.
Reslut
As a result, you should get the following application form with the possibility of filtering records in the table by date and time.