Evgenii Legotckoi
Evgenii LegotckoiAug. 30, 2015, 3:40 a.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.

#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.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
sf

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:90points,
  • Rating points8
МВ

Qt - Test 001. Signals and slots

  • Result:68points,
  • Rating points-1
ЛС

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
Last comments
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Now discuss on the forum
J
JacobFibOct. 17, 2024, 3:27 a.m.
добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
JW
Jhon WickOct. 1, 2024, 3:52 p.m.
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл ГусаревSept. 27, 2024, 9:09 a.m.
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
FynjyJuly 22, 2024, 4:15 a.m.
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Follow us in social networks