IscanderChe
IscanderCheJuly 15, 2019, 7:32 a.m.

Simple Tracker project. Part 2: project structure

The general structure is shown below.

I changed the name of the project. But in the titles of articles and tags, I will still leave "Simple tracker" so that there is no confusion.

The project consists of client and server subprojects and a testing subproject. The main project file looks like this.

TEMPLATE = subdirs

CONFIG   += ordered

SUBDIRS += ICTrackerServer ICTrackerClient tests

It is worth noting the common.pri file, which is visible to the client and server subprojects (and will also be included in the tests as needed). There I entered additional directives, peeped in other projects.

# Переменная PWD разворачивается в путь к файлу *.pro/*.pri, в котором используется
BUILD_DIR = $${PWD}/build

# В зависимости от типа билда, debug или release, устанавливаем соответствующее
# значение переменной BUILD_TYPE
CONFIG(release, debug|release){
    message(Release)
    BUILD_TYPE = release
}else{
    message(Debug)
    BUILD_TYPE = debug
}

DEST_BINS = $${BUILD_DIR}/$${BUILD_TYPE}

# В зависимости от платформы, на которой собираем проект, устанавливаем
# расположение исполняемых файлов.
# Регулярное выражение "s,/,\\,g" в SOME_VAR ~= s,/,\\,g означает
# "заменить в переменной SOME_VAR прямой слэш ("/") на обратный слэш ("\")".
win32 {
    DEST_BINS ~= s,/,\\,g
    DESTDIR = $${DEST_BINS}
}

linux {
    DESTDIR = $${DEST_BINS}
}

# Остальные файлы, которые генерируются по ходу сборки, выносим за пределы репозитория.
# Переменная OUT_PWD разворачивается в путь построения билда,
# заданный в Qt Creator в настройках проекта.
MOC_DIR        = $${OUT_PWD}/$${BUILD_TYPE}/moc
UI_DIR         = $${OUT_PWD}/$${BUILD_TYPE}/ui
UI_HEADERS_DIR = $${OUT_PWD}/$${BUILD_TYPE}/ui
UI_SOURCES_DIR = $${OUT_PWD}/$${BUILD_TYPE}/ui
OBJECTS_DIR    = $${OUT_PWD}/$${BUILD_TYPE}/obj
RCC_DIR        = $${OUT_PWD}/$${BUILD_TYPE}/rcc

Thus, when compiling a project in debug mode, the folder structure may look something like this.

Next to the source folders, a build folder is formed with two subfolders debug and release, where only executable files are written.

The remaining files are taken out of the project tree.

I placed the common.pri file in the root of the project and included it in the pro files of the subprojects using the include directive.

include(../common.pri)

Now let's look at subprojects.

The client, apart from the pro and pri files, has only main.cpp. Since the client is assumed to be console, most likely, apart from auxiliary functions, nothing else is needed.

It remains only to add network support to the pro-file.

QT += network

The server has more tasks, and therefore its structure is more complicated. There is a TrackerServer class here, which is responsible for creating the tracker GUI and server operation. The image also shows the DataBase class, which is responsible for working with the database. Also, in the course of development, classes will be added to implement dialog boxes.

Here in the pro-file, in addition to network support, you need to add SQL support.

QT += sql network

The tests subproject itself will consist of subprojects, so the following is written in the pro file:

TEMPLATE = subdirs

CONFIG   += ordered

SUBDIRS +=

With the structure of the project, in the first approximation, it is finished. In the next part, I will describe the database and its testing.

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!

Evgenii Legotckoi
  • July 16, 2019, 4:05 a.m.

Я правильно понимаю, что сервер будет формироавть API для доступа клиентов, а клиенты не будут иметь прямого доступа к базе данных?

Вы используете JSON для формирования сообщений между сервером и клиентами?

IscanderChe
  • July 16, 2019, 12:36 p.m.

Да, прямой доступ не предполагается. Впрочем, можно, конечно, и напрямую. Всё равно всё локально происходит. Проблема в том, как донести сведения об изменениях в базе, которые вносит клиент, до модели QSqlTableModel, которая в сервере? Если как-то можно, то тогда надобность в QLocalServer и QLocalSocket, конечно, отпадает.

Нет, JSON не использую. Просто QByteArray и QDataStream. От клиента серверу передётся всего три параметра: наименование проекта, номер закрываемой задачи и номер ревизии, закрывающей задачу.

Evgenii Legotckoi
  • July 16, 2019, 2:47 p.m.

Лучше API )))

Кстати, по использованию QLocalServer и QLocalSocket на сайте нет статей, было бы очень полезно и хорошо пошло бы в раздел Qt.

IscanderChe
  • July 16, 2019, 3:05 p.m.
  • (edited)

Так пример с QLocalServer и QLocalSocket я целиком переписал с QTcpSocket и QTcpServer из книги Шлее. Принципиальное отличие - где коннект ставить. :)) Разве что на это упор сделать. Но я могу этот пример кинуть с поправкой на то, откуда оригинал взят.

Evgenii Legotckoi
  • July 16, 2019, 3:15 p.m.

Конечно )) На самом деле не все читали Шлее... я например не читал ))

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 2:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

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

  • Result:46points,
  • Rating points-6
Last comments
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> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks