Evgenii Legotckoi
Aug. 30, 2015, 1:40 p.m.

Qt/C++ - Lesson 007. Filter for records in QSqlTableModel

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.

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. ***
  5.  
  6. namespace Ui {
  7. class MainWindow;
  8. }
  9.  
  10. class MainWindow : public QMainWindow
  11. {
  12. Q_OBJECT
  13.  
  14. ***
  15.  
  16. private slots:
  17. void on_pushButton_clicked();
  18.  
  19. ***
  20.  
  21. };
  22.  
  23. #endif // MAINWINDOW_H

mainwindow.cpp

This file is changed only partially, and one method is added for processing SLOT button is pressed.

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3.  
  4. MainWindow::MainWindow(QWidget *parent) :
  5. QMainWindow(parent),
  6. ui(new Ui::MainWindow)
  7. {
  8. ***
  9. }
  10.  
  11. MainWindow::~MainWindow()
  12. {
  13. delete ui;
  14. }
  15.  
  16. void MainWindow::setupModel(const QString &tableName, const QStringList &headers)
  17. {
  18. ***
  19. }
  20.  
  21. void MainWindow::createUI()
  22. {
  23. ***
  24.  
  25. ui->dateEditFROM->setDate(QDate::currentDate());
  26. ui->dateEditTO->setDate(QDate::currentDate());
  27. on_pushButton_clicked();
  28. }
  29.  
  30. /* The method for processing a button is pressed and part-filter model to represent tabular data
  31. * */
  32. void MainWindow::on_pushButton_clicked()
  33. {
  34. /* Установка фильтра представляет из себя часть SQL запроса
  35. * который начинается после слова WHERE в SQL запросе.
  36. * Следовательно для специалистов, работавших с SQL не составит труда
  37. * сформировать нужный фильтр
  38. * */
  39. model->setFilter(QString( TABLE_DATE " between '%1' and '%2' and "
  40. TABLE_TIME " between '%3' and '%4'")
  41. .arg(ui->dateEditFROM->date().toString("yyyy-MM-dd"),
  42. ui->dateEditTO->date().toString("yyyy-MM-dd"),
  43. ui->timeEditFROM->time().toString("hh:mm:ss"),
  44. ui->timeEditTO->time().toString("hh:mm:ss")));
  45. model->select();
  46. }

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.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html