Compare commits
No commits in common. "main" and "1ed1c09ed3c00e5357a2abf105f2412730c0bd59" have entirely different histories.
main
...
1ed1c09ed3
38 changed files with 1 additions and 1528 deletions
80
README.md
80
README.md
|
|
@ -1,80 +0,0 @@
|
||||||
# Лабораторные работы — Деев
|
|
||||||
|
|
||||||
## Лабораторная работа 1 — Django REST API
|
|
||||||
|
|
||||||
**Расположение:** `lab-1/`
|
|
||||||
|
|
||||||
Django-приложение с REST API для викторины. PostgreSQL, без Docker.
|
|
||||||
|
|
||||||
**Запуск:**
|
|
||||||
```bash
|
|
||||||
pip install -r requirements.txt
|
|
||||||
python manage.py migrate
|
|
||||||
python manage.py runserver
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Лабораторная работа 2 — Docker
|
|
||||||
|
|
||||||
**Расположение:** `lab-2/`
|
|
||||||
|
|
||||||
То же приложение, упакованное в Docker-контейнеры. Три варианта запуска:
|
|
||||||
|
|
||||||
| Папка | Описание |
|
|
||||||
|-------|----------|
|
|
||||||
| `local/` | Сборка образов из исходников, PostgreSQL в контейнере |
|
|
||||||
| `web_lite/` | Готовые образы с `dcr.deev.su`, PostgreSQL внешний |
|
|
||||||
| `web_pg/` | Готовые образы с `dcr.deev.su`, PostgreSQL в контейнере |
|
|
||||||
|
|
||||||
**Образы на registry:**
|
|
||||||
- `dcr.deev.su/deevev/lab2-backend:1.0.0`
|
|
||||||
- `dcr.deev.su/deevev/lab2-nginx:1.0.0`
|
|
||||||
|
|
||||||
**Запуск (любой из вариантов):**
|
|
||||||
```bash
|
|
||||||
cd lab-2/local # или web_lite / web_pg
|
|
||||||
docker compose up
|
|
||||||
```
|
|
||||||
|
|
||||||
Перед запуском `web_lite` и `web_pg` нужен файл `.env` — пример в `lab-2/local/.env`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Лабораторная работа 3 — Qt GUI клиент
|
|
||||||
|
|
||||||
**Расположение:** `lab-3/`
|
|
||||||
|
|
||||||
Qt6-приложение на C++ — графический клиент к REST API из Лаб-1.
|
|
||||||
Демонстрирует паттерны проектирования **Singleton** и **Adapter**.
|
|
||||||
|
|
||||||
**Стек:** Qt 6, C++17, QNetworkAccessManager, CMake
|
|
||||||
|
|
||||||
**Паттерны:**
|
|
||||||
- **Singleton** — `ApiClient` существует в единственном экземпляре (Meyers' Singleton)
|
|
||||||
- **Adapter** — `QuizJsonAdapter` конвертирует `QJsonObject` → `Quiz`
|
|
||||||
|
|
||||||
**5 HTTP-методов:**
|
|
||||||
|
|
||||||
| Кнопка | Метод | Endpoint |
|
|
||||||
|--------|-------|----------|
|
|
||||||
| Все тесты | GET | `/api/quiz/` |
|
|
||||||
| По ID | GET | `/api/quiz/:id/` |
|
|
||||||
| Создать | POST | `/api/quiz/` |
|
|
||||||
| Обновить | PUT | `/api/quiz/:id/` |
|
|
||||||
| Удалить | DELETE | `/api/quiz/:id/` |
|
|
||||||
|
|
||||||
**Сборка:**
|
|
||||||
```bash
|
|
||||||
cd lab-3
|
|
||||||
cmake -B build
|
|
||||||
cmake --build build
|
|
||||||
```
|
|
||||||
|
|
||||||
**Запуск бэкенда перед использованием:**
|
|
||||||
```bash
|
|
||||||
cd lab-2/web_lite
|
|
||||||
docker compose up
|
|
||||||
```
|
|
||||||
|
|
||||||
Приложение подключается к `http://localhost:80`.
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
.env
|
|
||||||
certs/
|
|
||||||
__pycache__/
|
|
||||||
*.pyc
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
{
|
|
||||||
auto_https off
|
|
||||||
}
|
|
||||||
|
|
||||||
:80 {
|
|
||||||
redir https://{host}{uri} permanent
|
|
||||||
}
|
|
||||||
|
|
||||||
:443 {
|
|
||||||
tls /run/secrets/lab2_crt /run/secrets/lab2_key
|
|
||||||
|
|
||||||
handle_path /static/* {
|
|
||||||
root * /staticfiles
|
|
||||||
file_server
|
|
||||||
}
|
|
||||||
|
|
||||||
handle /admin/* {
|
|
||||||
reverse_proxy backend_service:8000
|
|
||||||
}
|
|
||||||
|
|
||||||
handle /api/* {
|
|
||||||
reverse_proxy backend_service:8000
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
FROM python:3.12-slim
|
|
||||||
|
|
||||||
ENV PYTHONDONTWRITEBYTECODE=1
|
|
||||||
ENV PYTHONUNBUFFERED=1
|
|
||||||
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
COPY requirements.txt .
|
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
|
||||||
|
|
||||||
COPY . .
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
"""
|
|
||||||
ASGI config for lab1 project.
|
|
||||||
|
|
||||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
|
||||||
|
|
||||||
For more information on this file, see
|
|
||||||
https://docs.djangoproject.com/en/6.0/howto/deployment/asgi/
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
|
|
||||||
from django.core.asgi import get_asgi_application
|
|
||||||
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lab1.settings')
|
|
||||||
|
|
||||||
application = get_asgi_application()
|
|
||||||
|
|
@ -1,133 +0,0 @@
|
||||||
"""
|
|
||||||
Django settings for lab1 project.
|
|
||||||
|
|
||||||
Generated by 'django-admin startproject' using Django 6.0.3.
|
|
||||||
|
|
||||||
For more information on this file, see
|
|
||||||
https://docs.djangoproject.com/en/6.0/topics/settings/
|
|
||||||
|
|
||||||
For the full list of settings and their values, see
|
|
||||||
https://docs.djangoproject.com/en/6.0/ref/settings/
|
|
||||||
"""
|
|
||||||
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
|
||||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
||||||
|
|
||||||
|
|
||||||
# Quick-start development settings - unsuitable for production
|
|
||||||
# See https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/
|
|
||||||
|
|
||||||
# SECURITY WARNING: keep the secret key used in production secret!
|
|
||||||
SECRET_KEY = 'django-insecure--xqwhdo2$)n*y3yk=d*vmwx6nuwt8h=m5@_og_uzj+11^hu7))'
|
|
||||||
|
|
||||||
# SECURITY WARNING: don't run with debug turned on in production!
|
|
||||||
DEBUG = True
|
|
||||||
|
|
||||||
ALLOWED_HOSTS = ['*']
|
|
||||||
CSRF_TRUSTED_ORIGINS = ['http://localhost', 'https://localhost']
|
|
||||||
|
|
||||||
|
|
||||||
# Application definition
|
|
||||||
|
|
||||||
INSTALLED_APPS = [
|
|
||||||
'django.contrib.admin',
|
|
||||||
'django.contrib.auth',
|
|
||||||
'django.contrib.contenttypes',
|
|
||||||
'django.contrib.sessions',
|
|
||||||
'django.contrib.messages',
|
|
||||||
'django.contrib.staticfiles',
|
|
||||||
|
|
||||||
'rest_framework',
|
|
||||||
'quiz',
|
|
||||||
]
|
|
||||||
|
|
||||||
MIDDLEWARE = [
|
|
||||||
'django.middleware.security.SecurityMiddleware',
|
|
||||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
|
||||||
'django.middleware.common.CommonMiddleware',
|
|
||||||
'django.middleware.csrf.CsrfViewMiddleware',
|
|
||||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
|
||||||
'django.contrib.messages.middleware.MessageMiddleware',
|
|
||||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
|
||||||
]
|
|
||||||
|
|
||||||
ROOT_URLCONF = 'lab1.urls'
|
|
||||||
|
|
||||||
TEMPLATES = [
|
|
||||||
{
|
|
||||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
|
||||||
'DIRS': [],
|
|
||||||
'APP_DIRS': True,
|
|
||||||
'OPTIONS': {
|
|
||||||
'context_processors': [
|
|
||||||
'django.template.context_processors.request',
|
|
||||||
'django.contrib.auth.context_processors.auth',
|
|
||||||
'django.contrib.messages.context_processors.messages',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
WSGI_APPLICATION = 'lab1.wsgi.application'
|
|
||||||
|
|
||||||
|
|
||||||
# Database
|
|
||||||
# https://docs.djangoproject.com/en/6.0/ref/settings/#databases
|
|
||||||
|
|
||||||
import os
|
|
||||||
|
|
||||||
DATABASES = {
|
|
||||||
'default': {
|
|
||||||
'ENGINE': 'django.db.backends.postgresql',
|
|
||||||
'NAME': os.environ.get('POSTGRES_DB', 'lab_db'),
|
|
||||||
'USER': os.environ.get('POSTGRES_USER', 'django'),
|
|
||||||
'PASSWORD': os.environ.get('POSTGRES_PASSWORD', 'password'),
|
|
||||||
'HOST': os.environ.get('POSTGRES_HOST', 'postgres_service'),
|
|
||||||
'PORT': os.environ.get('POSTGRES_PORT', 5432),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# Password validation
|
|
||||||
# https://docs.djangoproject.com/en/6.0/ref/settings/#auth-password-validators
|
|
||||||
|
|
||||||
AUTH_PASSWORD_VALIDATORS = [
|
|
||||||
{
|
|
||||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
# Internationalization
|
|
||||||
# https://docs.djangoproject.com/en/6.0/topics/i18n/
|
|
||||||
|
|
||||||
LANGUAGE_CODE = 'ru-ru'
|
|
||||||
|
|
||||||
TIME_ZONE = 'UTC'
|
|
||||||
|
|
||||||
USE_I18N = True
|
|
||||||
|
|
||||||
USE_TZ = True
|
|
||||||
|
|
||||||
|
|
||||||
# Static files (CSS, JavaScript, Images)
|
|
||||||
# https://docs.djangoproject.com/en/6.0/howto/static-files/
|
|
||||||
|
|
||||||
STATIC_URL = 'static/'
|
|
||||||
STATIC_ROOT = BASE_DIR / 'staticfiles'
|
|
||||||
|
|
||||||
# Default primary key field type
|
|
||||||
# https://docs.djangoproject.com/en/6.0/ref/settings/#default-auto-field
|
|
||||||
|
|
||||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
from django.contrib import admin
|
|
||||||
from django.urls import path, include
|
|
||||||
from rest_framework import routers
|
|
||||||
from quiz.views import QuizViewSet
|
|
||||||
|
|
||||||
router = routers.DefaultRouter()
|
|
||||||
router.register(r'quiz', QuizViewSet)
|
|
||||||
|
|
||||||
urlpatterns = [
|
|
||||||
path('admin/', admin.site.urls),
|
|
||||||
path('api/', include(router.urls)),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
"""
|
|
||||||
WSGI config for lab1 project.
|
|
||||||
|
|
||||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
|
||||||
|
|
||||||
For more information on this file, see
|
|
||||||
https://docs.djangoproject.com/en/6.0/howto/deployment/wsgi/
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
|
|
||||||
from django.core.wsgi import get_wsgi_application
|
|
||||||
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lab1.settings')
|
|
||||||
|
|
||||||
application = get_wsgi_application()
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
#!/usr/bin/env python
|
|
||||||
"""Django's command-line utility for administrative tasks."""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
"""Run administrative tasks."""
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lab1.settings')
|
|
||||||
try:
|
|
||||||
from django.core.management import execute_from_command_line
|
|
||||||
except ImportError as exc:
|
|
||||||
raise ImportError(
|
|
||||||
"Couldn't import Django. Are you sure it's installed and "
|
|
||||||
"available on your PYTHONPATH environment variable? Did you "
|
|
||||||
"forget to activate a virtual environment?"
|
|
||||||
) from exc
|
|
||||||
execute_from_command_line(sys.argv)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main()
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
from django.contrib import admin
|
|
||||||
from .models import Quiz
|
|
||||||
|
|
||||||
admin.site.register(Quiz)
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
from django.apps import AppConfig
|
|
||||||
|
|
||||||
|
|
||||||
class QuizConfig(AppConfig):
|
|
||||||
name = 'quiz'
|
|
||||||
|
|
@ -1,18 +0,0 @@
|
||||||
import random
|
|
||||||
from .models import Quiz
|
|
||||||
from django.db import transaction
|
|
||||||
from faker import Faker
|
|
||||||
|
|
||||||
fk = Faker()
|
|
||||||
|
|
||||||
def gentestdata():
|
|
||||||
with transaction.atomic():
|
|
||||||
for i in range(100):
|
|
||||||
new_quiz = Quiz()
|
|
||||||
new_quiz.title = fk.sentence(nb_words=4)
|
|
||||||
new_quiz.description = fk.paragraph()
|
|
||||||
new_quiz.author = fk.name()
|
|
||||||
new_quiz.time_limit = random.randint(5, 60)
|
|
||||||
new_quiz.is_published = random.random() > 0.5
|
|
||||||
new_quiz.save()
|
|
||||||
print('Сделана генерация')
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
# Generated by Django 6.0.3 on 2026-03-05 08:16
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
initial = True
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='Quiz',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('title', models.CharField(max_length=200)),
|
|
||||||
('description', models.TextField()),
|
|
||||||
('author', models.CharField(max_length=100)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('time_limit', models.IntegerField(help_text='Ограничение по времени в минутах')),
|
|
||||||
('is_published', models.BooleanField(default=False)),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
]
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
from django.db import models
|
|
||||||
|
|
||||||
# Create your models here.
|
|
||||||
|
|
||||||
class Quiz(models.Model):
|
|
||||||
title = models.CharField(max_length=200)
|
|
||||||
description = models.TextField()
|
|
||||||
author = models.CharField(max_length=100)
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
time_limit = models.IntegerField(help_text='Ограничение по времени в минутах')
|
|
||||||
is_published = models.BooleanField(default=False)
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.title
|
|
||||||
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
from rest_framework import serializers
|
|
||||||
from .models import Quiz
|
|
||||||
|
|
||||||
class QuizSerializer(serializers.ModelSerializer):
|
|
||||||
class Meta:
|
|
||||||
model = Quiz
|
|
||||||
fields = '__all__'
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
from django.test import TestCase
|
|
||||||
|
|
||||||
# Create your tests here.
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
from django.shortcuts import render
|
|
||||||
|
|
||||||
from rest_framework import viewsets
|
|
||||||
from .models import Quiz
|
|
||||||
from .serializers import QuizSerializer
|
|
||||||
|
|
||||||
class QuizViewSet(viewsets.ModelViewSet):
|
|
||||||
queryset = Quiz.objects.all()
|
|
||||||
serializer_class = QuizSerializer
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
Django
|
|
||||||
djangorestframework
|
|
||||||
markdown
|
|
||||||
django-filter
|
|
||||||
django-cors-headers
|
|
||||||
psycopg[binary,pool]
|
|
||||||
faker
|
|
||||||
gunicorn
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
name: lab2-caddy
|
|
||||||
|
|
||||||
secrets:
|
|
||||||
lab2_crt:
|
|
||||||
file: ./certs/lab2.crt
|
|
||||||
lab2_key:
|
|
||||||
file: ./certs/lab2.key
|
|
||||||
|
|
||||||
services:
|
|
||||||
postgres_service:
|
|
||||||
image: postgres:16-alpine
|
|
||||||
env_file:
|
|
||||||
- .env
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
|
|
||||||
interval: 10s
|
|
||||||
timeout: 30s
|
|
||||||
retries: 5
|
|
||||||
volumes:
|
|
||||||
- postgres_data:/var/lib/postgresql/data
|
|
||||||
|
|
||||||
backend_service:
|
|
||||||
build: ./backend
|
|
||||||
command: >
|
|
||||||
sh -c "python manage.py migrate &&
|
|
||||||
python manage.py shell -c 'from quiz.gentestdata import gentestdata; gentestdata()' &&
|
|
||||||
python manage.py collectstatic --no-input &&
|
|
||||||
gunicorn lab1.wsgi:application --bind 0.0.0.0:8000"
|
|
||||||
volumes:
|
|
||||||
- static_volume:/app/staticfiles
|
|
||||||
env_file:
|
|
||||||
- .env
|
|
||||||
depends_on:
|
|
||||||
postgres_service:
|
|
||||||
condition: service_healthy
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
caddy_service:
|
|
||||||
image: caddy:alpine
|
|
||||||
ports:
|
|
||||||
- "80:80"
|
|
||||||
- "443:443"
|
|
||||||
volumes:
|
|
||||||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
|
||||||
- static_volume:/staticfiles:ro
|
|
||||||
secrets:
|
|
||||||
- lab2_crt
|
|
||||||
- lab2_key
|
|
||||||
depends_on:
|
|
||||||
- backend_service
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
static_volume:
|
|
||||||
postgres_data:
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
|
|
||||||
set -e
|
|
||||||
mkdir -p certs
|
|
||||||
|
|
||||||
# 1. Генерация корневого сертификата root.crt и его rsa-ключа root.key
|
|
||||||
openssl req -x509 -new -nodes -newkey rsa:2048 \
|
|
||||||
-keyout certs/root.key -days 3650 \
|
|
||||||
-out certs/root.crt -subj "//CN=Root CA"
|
|
||||||
|
|
||||||
# 2. Генерация rsa-ключа для сертификата сервера и вспомогательного CSR-файла (Certificate Signing Request) на основе этого ключа
|
|
||||||
openssl req -new -nodes -newkey rsa:2048 \
|
|
||||||
-keyout certs/lab2.key -out certs/lab2.csr \
|
|
||||||
-subj "//CN=lab2 server cert"
|
|
||||||
|
|
||||||
# 3. Собственно, генерация сертификата сервера *.crt из *.csr-файла, сгенерированного выше
|
|
||||||
echo "subjectAltName=DNS:localhost,IP:127.0.0.1" > certs/extfile.txt
|
|
||||||
openssl x509 -req -in certs/lab2.csr -days 3650 \
|
|
||||||
-CA certs/root.crt -CAkey certs/root.key \
|
|
||||||
-CAcreateserial -out certs/lab2.crt \
|
|
||||||
-sha256 -extfile certs/extfile.txt
|
|
||||||
rm certs/extfile.txt
|
|
||||||
|
|
||||||
# 4. Удаление вспомогательного CSR-файла
|
|
||||||
rm certs/lab2.csr
|
|
||||||
echo "Done. Certificates written to ./certs/"
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -1,76 +0,0 @@
|
||||||
cmake_minimum_required(VERSION 3.16)
|
|
||||||
|
|
||||||
project(lab-3 VERSION 0.1 LANGUAGES CXX)
|
|
||||||
|
|
||||||
set(CMAKE_AUTOUIC ON)
|
|
||||||
set(CMAKE_AUTOMOC ON)
|
|
||||||
set(CMAKE_AUTORCC ON)
|
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
|
||||||
|
|
||||||
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets Network LinguistTools)
|
|
||||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets Network LinguistTools)
|
|
||||||
|
|
||||||
set(TS_FILES lab-3_ru_RU.ts)
|
|
||||||
|
|
||||||
set(PROJECT_SOURCES
|
|
||||||
main.cpp
|
|
||||||
mainwindow.cpp
|
|
||||||
mainwindow.h
|
|
||||||
mainwindow.ui
|
|
||||||
quiz.h
|
|
||||||
iquiz_adapter.h
|
|
||||||
quiz_json_adapter.h
|
|
||||||
quiz_json_adapter.cpp
|
|
||||||
api_client.h
|
|
||||||
api_client.cpp
|
|
||||||
resources.qrc
|
|
||||||
${TS_FILES}
|
|
||||||
)
|
|
||||||
|
|
||||||
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
|
|
||||||
qt_add_executable(lab-3
|
|
||||||
MANUAL_FINALIZATION
|
|
||||||
${PROJECT_SOURCES}
|
|
||||||
)
|
|
||||||
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
|
||||||
else()
|
|
||||||
if(ANDROID)
|
|
||||||
add_library(lab-3 SHARED
|
|
||||||
${PROJECT_SOURCES}
|
|
||||||
)
|
|
||||||
else()
|
|
||||||
add_executable(lab-3
|
|
||||||
${PROJECT_SOURCES}
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
|
||||||
endif()
|
|
||||||
|
|
||||||
target_link_libraries(lab-3 PRIVATE
|
|
||||||
Qt${QT_VERSION_MAJOR}::Widgets
|
|
||||||
Qt${QT_VERSION_MAJOR}::Network
|
|
||||||
)
|
|
||||||
|
|
||||||
if(${QT_VERSION} VERSION_LESS 6.1.0)
|
|
||||||
set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.lab-3)
|
|
||||||
endif()
|
|
||||||
set_target_properties(lab-3 PROPERTIES
|
|
||||||
${BUNDLE_ID_OPTION}
|
|
||||||
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
|
|
||||||
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
|
|
||||||
MACOSX_BUNDLE TRUE
|
|
||||||
WIN32_EXECUTABLE TRUE
|
|
||||||
)
|
|
||||||
|
|
||||||
include(GNUInstallDirs)
|
|
||||||
install(TARGETS lab-3
|
|
||||||
BUNDLE DESTINATION .
|
|
||||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
|
||||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
|
||||||
)
|
|
||||||
|
|
||||||
if(QT_VERSION_MAJOR EQUAL 6)
|
|
||||||
qt_finalize_executable(lab-3)
|
|
||||||
endif()
|
|
||||||
|
|
@ -1,158 +0,0 @@
|
||||||
#include "api_client.h"
|
|
||||||
#include "quiz_json_adapter.h"
|
|
||||||
|
|
||||||
#include <QNetworkReply>
|
|
||||||
#include <QNetworkRequest>
|
|
||||||
#include <QJsonDocument>
|
|
||||||
#include <QJsonArray>
|
|
||||||
#include <QJsonObject>
|
|
||||||
#include <QDebug>
|
|
||||||
|
|
||||||
// Реализация паттерна Синглтон
|
|
||||||
ApiClient &ApiClient::instance()
|
|
||||||
{
|
|
||||||
static ApiClient s_instance;
|
|
||||||
return s_instance;
|
|
||||||
}
|
|
||||||
|
|
||||||
ApiClient::ApiClient(QObject *parent)
|
|
||||||
: QObject(parent)
|
|
||||||
, m_manager(new QNetworkAccessManager(this))
|
|
||||||
, m_adapter(new QuizJsonAdapter())
|
|
||||||
, m_baseUrl("http://localhost:80")
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
ApiClient::~ApiClient()
|
|
||||||
{
|
|
||||||
delete m_adapter;
|
|
||||||
}
|
|
||||||
|
|
||||||
// fetchQuizzes — GET /api/quiz/
|
|
||||||
void ApiClient::fetchQuizzes()
|
|
||||||
{
|
|
||||||
QNetworkRequest request(QUrl(m_baseUrl + "/api/quiz/"));
|
|
||||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
|
||||||
|
|
||||||
QNetworkReply *reply = m_manager->get(request);
|
|
||||||
|
|
||||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
|
||||||
reply->deleteLater();
|
|
||||||
|
|
||||||
if (reply->error() != QNetworkReply::NoError) {
|
|
||||||
emit errorOccurred(reply->errorString());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// reply->readAll() — читаем весь буфер HTTP-ответа
|
|
||||||
QByteArray rawData = reply->readAll();
|
|
||||||
QJsonDocument doc = QJsonDocument::fromJson(rawData);
|
|
||||||
|
|
||||||
if (!doc.isArray()) {
|
|
||||||
emit errorOccurred("Unexpected JSON format: array expected");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
QList<Quiz> quizzes = m_adapter->toQuizList(doc.array());
|
|
||||||
emit quizzesReceived(quizzes);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// fetchQuiz — GET /api/quiz/:id/
|
|
||||||
void ApiClient::fetchQuiz(int id)
|
|
||||||
{
|
|
||||||
QNetworkRequest request(QUrl(m_baseUrl + "/api/quiz/" + QString::number(id) + "/"));
|
|
||||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
|
||||||
|
|
||||||
QNetworkReply *reply = m_manager->get(request);
|
|
||||||
|
|
||||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
|
||||||
reply->deleteLater();
|
|
||||||
|
|
||||||
if (reply->error() != QNetworkReply::NoError) {
|
|
||||||
emit errorOccurred(reply->errorString());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
QByteArray rawData = reply->readAll();
|
|
||||||
QJsonDocument doc = QJsonDocument::fromJson(rawData);
|
|
||||||
|
|
||||||
if (!doc.isObject()) {
|
|
||||||
emit errorOccurred("Unexpected JSON format: object expected");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
emit quizReceived(m_adapter->toQuiz(doc.object()));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// createQuiz — POST /api/quiz/
|
|
||||||
void ApiClient::createQuiz(const QJsonObject &data)
|
|
||||||
{
|
|
||||||
QNetworkRequest request(QUrl(m_baseUrl + "/api/quiz/"));
|
|
||||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
|
||||||
|
|
||||||
QByteArray body = QJsonDocument(data).toJson(QJsonDocument::Compact);
|
|
||||||
QNetworkReply *reply = m_manager->post(request, body);
|
|
||||||
|
|
||||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
|
||||||
reply->deleteLater();
|
|
||||||
if (reply->error() != QNetworkReply::NoError) {
|
|
||||||
emit errorOccurred(reply->errorString());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
QByteArray rawData = reply->readAll();
|
|
||||||
QJsonDocument doc = QJsonDocument::fromJson(rawData);
|
|
||||||
if (!doc.isObject()) {
|
|
||||||
emit errorOccurred("POST: unexpected JSON format");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
emit quizCreated(m_adapter->toQuiz(doc.object()));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// updateQuiz — PUT /api/quiz/:id/
|
|
||||||
void ApiClient::updateQuiz(int id, const QJsonObject &data)
|
|
||||||
{
|
|
||||||
QNetworkRequest request(QUrl(m_baseUrl + "/api/quiz/" + QString::number(id) + "/"));
|
|
||||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
|
||||||
|
|
||||||
QByteArray body = QJsonDocument(data).toJson(QJsonDocument::Compact);
|
|
||||||
QNetworkReply *reply = m_manager->put(request, body);
|
|
||||||
|
|
||||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
|
||||||
reply->deleteLater();
|
|
||||||
if (reply->error() != QNetworkReply::NoError) {
|
|
||||||
emit errorOccurred(reply->errorString());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
QByteArray rawData = reply->readAll();
|
|
||||||
QJsonDocument doc = QJsonDocument::fromJson(rawData);
|
|
||||||
if (!doc.isObject()) {
|
|
||||||
emit errorOccurred("PUT: unexpected JSON format");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
emit quizUpdated(m_adapter->toQuiz(doc.object()));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// deleteQuiz — DELETE /api/quiz/:id/
|
|
||||||
void ApiClient::deleteQuiz(int id)
|
|
||||||
{
|
|
||||||
QNetworkRequest request(QUrl(m_baseUrl + "/api/quiz/" + QString::number(id) + "/"));
|
|
||||||
QNetworkReply *reply = m_manager->deleteResource(request);
|
|
||||||
|
|
||||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
|
||||||
reply->deleteLater();
|
|
||||||
if (reply->error() != QNetworkReply::NoError) {
|
|
||||||
emit errorOccurred(reply->errorString());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
QByteArray rawData = reply->readAll();
|
|
||||||
QJsonDocument doc = QJsonDocument::fromJson(rawData);
|
|
||||||
QString message = "Тест удалён";
|
|
||||||
if (doc.isObject() && doc.object().contains("detail"))
|
|
||||||
message = doc.object()["detail"].toString();
|
|
||||||
emit quizDeleted(message);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <QObject>
|
|
||||||
#include <QNetworkAccessManager>
|
|
||||||
#include <QJsonObject>
|
|
||||||
#include <QList>
|
|
||||||
#include "quiz.h"
|
|
||||||
#include "iquiz_adapter.h"
|
|
||||||
|
|
||||||
class ApiClient : public QObject
|
|
||||||
{
|
|
||||||
Q_OBJECT
|
|
||||||
|
|
||||||
public:
|
|
||||||
static ApiClient &instance();
|
|
||||||
|
|
||||||
// GET /api/quiz/
|
|
||||||
void fetchQuizzes();
|
|
||||||
|
|
||||||
// GET /api/quiz/:id/
|
|
||||||
void fetchQuiz(int id);
|
|
||||||
|
|
||||||
// POST /api/quiz/
|
|
||||||
void createQuiz(const QJsonObject &data);
|
|
||||||
|
|
||||||
// PUT /api/quiz/:id/
|
|
||||||
void updateQuiz(int id, const QJsonObject &data);
|
|
||||||
|
|
||||||
// DELETE /api/quiz/:id/
|
|
||||||
void deleteQuiz(int id);
|
|
||||||
|
|
||||||
signals:
|
|
||||||
void quizzesReceived(QList<Quiz> quizzes);
|
|
||||||
void quizReceived(Quiz quiz);
|
|
||||||
void quizCreated(Quiz quiz);
|
|
||||||
void quizUpdated(Quiz quiz);
|
|
||||||
void quizDeleted(QString message);
|
|
||||||
void errorOccurred(QString error);
|
|
||||||
|
|
||||||
private:
|
|
||||||
explicit ApiClient(QObject *parent = nullptr);
|
|
||||||
~ApiClient() override;
|
|
||||||
|
|
||||||
ApiClient(const ApiClient &) = delete;
|
|
||||||
ApiClient &operator=(const ApiClient &) = delete;
|
|
||||||
|
|
||||||
QNetworkAccessManager *m_manager;
|
|
||||||
IQuizAdapter *m_adapter;
|
|
||||||
QString m_baseUrl;
|
|
||||||
};
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|
||||||
<rect width="64" height="64" rx="12" fill="#2563eb"/>
|
|
||||||
<rect x="12" y="14" width="40" height="36" rx="4" fill="white"/>
|
|
||||||
<rect x="18" y="20" width="28" height="3" rx="1.5" fill="#2563eb"/>
|
|
||||||
<rect x="18" y="27" width="20" height="3" rx="1.5" fill="#93c5fd"/>
|
|
||||||
<rect x="18" y="34" width="24" height="3" rx="1.5" fill="#93c5fd"/>
|
|
||||||
<circle cx="48" cy="46" r="10" fill="#16a34a"/>
|
|
||||||
<polyline points="43,46 47,50 54,41" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 585 B |
|
|
@ -1,16 +0,0 @@
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <QJsonObject>
|
|
||||||
#include <QJsonArray>
|
|
||||||
#include <QList>
|
|
||||||
#include "quiz.h"
|
|
||||||
|
|
||||||
class IQuizAdapter
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
virtual ~IQuizAdapter() = default;
|
|
||||||
|
|
||||||
virtual Quiz toQuiz(const QJsonObject &json) const = 0;
|
|
||||||
|
|
||||||
virtual QList<Quiz> toQuizList(const QJsonArray &json) const = 0;
|
|
||||||
};
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<!DOCTYPE TS>
|
|
||||||
<TS version="2.1" language="ru_RU"></TS>
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
#include "mainwindow.h"
|
|
||||||
|
|
||||||
#include <QApplication>
|
|
||||||
#include <QLocale>
|
|
||||||
#include <QTranslator>
|
|
||||||
|
|
||||||
int main(int argc, char *argv[])
|
|
||||||
{
|
|
||||||
QApplication a(argc, argv);
|
|
||||||
|
|
||||||
QTranslator translator;
|
|
||||||
const QStringList uiLanguages = QLocale::system().uiLanguages();
|
|
||||||
for (const QString &locale : uiLanguages) {
|
|
||||||
const QString baseName = "lab-3_" + QLocale(locale).name();
|
|
||||||
if (translator.load(":/i18n/" + baseName)) {
|
|
||||||
a.installTranslator(&translator);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int result = 0;
|
|
||||||
{
|
|
||||||
MainWindow w;
|
|
||||||
w.show();
|
|
||||||
result = a.exec();
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
@ -1,414 +0,0 @@
|
||||||
#include "mainwindow.h"
|
|
||||||
#include "ui_mainwindow.h"
|
|
||||||
#include "api_client.h"
|
|
||||||
|
|
||||||
#include <QPushButton>
|
|
||||||
#include <QInputDialog>
|
|
||||||
#include <QDialog>
|
|
||||||
#include <QFormLayout>
|
|
||||||
#include <QVBoxLayout>
|
|
||||||
#include <QLineEdit>
|
|
||||||
#include <QTextEdit>
|
|
||||||
#include <QCheckBox>
|
|
||||||
#include <QSpinBox>
|
|
||||||
#include <QDialogButtonBox>
|
|
||||||
#include <QTableWidget>
|
|
||||||
#include <QTableWidgetItem>
|
|
||||||
#include <QHeaderView>
|
|
||||||
#include <QColor>
|
|
||||||
#include <QFont>
|
|
||||||
#include <QDebug>
|
|
||||||
|
|
||||||
static const int COL_ID = 0;
|
|
||||||
static const int COL_TITLE = 1;
|
|
||||||
static const int COL_AUTHOR = 2;
|
|
||||||
static const int COL_TIME = 3;
|
|
||||||
static const int COL_PUBLISHED = 4;
|
|
||||||
static const int COL_CREATED = 5;
|
|
||||||
static const int COL_DESCRIPTION = 6;
|
|
||||||
static const int COL_COUNT = 7;
|
|
||||||
|
|
||||||
MainWindow::MainWindow(QWidget *parent)
|
|
||||||
: QMainWindow(parent)
|
|
||||||
, ui(new Ui::MainWindow)
|
|
||||||
{
|
|
||||||
ui->setupUi(this);
|
|
||||||
setWindowIcon(QIcon(":/icons/app.svg"));
|
|
||||||
|
|
||||||
setupTable();
|
|
||||||
|
|
||||||
ui->tabWidget->tabBar()->hide();
|
|
||||||
|
|
||||||
// Кнопки переключения вида
|
|
||||||
auto *btnTable = new QPushButton("Таблица", this);
|
|
||||||
auto *btnText = new QPushButton("Текст", this);
|
|
||||||
|
|
||||||
QString activeStyle = "QPushButton{background:#1f2937;color:#f9fafb;border:1px solid #4b5563;border-radius:4px;padding:2px 12px;font-weight:bold;}";
|
|
||||||
QString inactiveStyle = "QPushButton{background:#111827;color:#6b7280;border:1px solid #374151;border-radius:4px;padding:2px 12px;}";
|
|
||||||
|
|
||||||
btnTable->setStyleSheet(activeStyle);
|
|
||||||
btnText->setStyleSheet(inactiveStyle);
|
|
||||||
btnTable->setFixedHeight(22);
|
|
||||||
btnText->setFixedHeight(22);
|
|
||||||
|
|
||||||
connect(btnTable, &QPushButton::clicked, this, [=]() {
|
|
||||||
ui->tabWidget->setCurrentIndex(0);
|
|
||||||
btnTable->setStyleSheet(activeStyle);
|
|
||||||
btnText->setStyleSheet(inactiveStyle);
|
|
||||||
});
|
|
||||||
connect(btnText, &QPushButton::clicked, this, [=]() {
|
|
||||||
ui->tabWidget->setCurrentIndex(1);
|
|
||||||
btnText->setStyleSheet(activeStyle);
|
|
||||||
btnTable->setStyleSheet(inactiveStyle);
|
|
||||||
});
|
|
||||||
|
|
||||||
statusBar()->addPermanentWidget(btnTable);
|
|
||||||
statusBar()->addPermanentWidget(btnText);
|
|
||||||
statusBar()->setStyleSheet("QStatusBar::item { border: none; }");
|
|
||||||
|
|
||||||
ApiClient &client = ApiClient::instance();
|
|
||||||
connect(&client, &ApiClient::quizzesReceived, this, &MainWindow::onQuizzesReceived);
|
|
||||||
connect(&client, &ApiClient::quizReceived, this, &MainWindow::onQuizReceived);
|
|
||||||
connect(&client, &ApiClient::quizCreated, this, &MainWindow::onQuizCreated);
|
|
||||||
connect(&client, &ApiClient::quizUpdated, this, &MainWindow::onQuizUpdated);
|
|
||||||
connect(&client, &ApiClient::quizDeleted, this, &MainWindow::onQuizDeleted);
|
|
||||||
connect(&client, &ApiClient::errorOccurred, this, &MainWindow::onError);
|
|
||||||
}
|
|
||||||
|
|
||||||
MainWindow::~MainWindow()
|
|
||||||
{
|
|
||||||
delete ui;
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::setupTable()
|
|
||||||
{
|
|
||||||
ui->tableWidget->setColumnCount(COL_COUNT);
|
|
||||||
ui->tableWidget->setHorizontalHeaderLabels({
|
|
||||||
"ID", "Название", "Автор", "Время (мин)", "Опубликован", "Создан", "Описание"
|
|
||||||
});
|
|
||||||
|
|
||||||
QHeaderView *header = ui->tableWidget->horizontalHeader();
|
|
||||||
header->setSectionResizeMode(COL_ID, QHeaderView::ResizeToContents);
|
|
||||||
header->setSectionResizeMode(COL_TITLE, QHeaderView::Stretch);
|
|
||||||
header->setSectionResizeMode(COL_AUTHOR, QHeaderView::ResizeToContents);
|
|
||||||
header->setSectionResizeMode(COL_TIME, QHeaderView::ResizeToContents);
|
|
||||||
header->setSectionResizeMode(COL_PUBLISHED, QHeaderView::ResizeToContents);
|
|
||||||
header->setSectionResizeMode(COL_CREATED, QHeaderView::ResizeToContents);
|
|
||||||
header->setSectionResizeMode(COL_DESCRIPTION, QHeaderView::Stretch);
|
|
||||||
|
|
||||||
ui->tableWidget->verticalHeader()->setVisible(false);
|
|
||||||
ui->tableWidget->setWordWrap(true);
|
|
||||||
ui->tableWidget->setTextElideMode(Qt::ElideNone);
|
|
||||||
ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Interactive);
|
|
||||||
ui->tableWidget->verticalHeader()->setDefaultSectionSize(52);
|
|
||||||
ui->tableWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
|
|
||||||
ui->tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Обработчики кнопок ────────────────────────────────────────────────────────
|
|
||||||
void MainWindow::on_btnGetAll_clicked()
|
|
||||||
{
|
|
||||||
++m_requestCount;
|
|
||||||
setStatus(QString("GET /api/quiz/… | Запросов: %1").arg(m_requestCount));
|
|
||||||
ApiClient::instance().fetchQuizzes();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::on_btnGetById_clicked()
|
|
||||||
{
|
|
||||||
bool ok;
|
|
||||||
int id = QInputDialog::getInt(this, "Get Quiz by ID", "ID теста:", 1, 1, 99999, 1, &ok);
|
|
||||||
if (!ok) return;
|
|
||||||
++m_requestCount;
|
|
||||||
setStatus(QString("GET /api/quiz/%1/… | Запросов: %2").arg(id).arg(m_requestCount));
|
|
||||||
ApiClient::instance().fetchQuiz(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::on_btnCreate_clicked()
|
|
||||||
{
|
|
||||||
QDialog dlg(this);
|
|
||||||
dlg.setWindowTitle("Создать тест — POST /api/quiz/");
|
|
||||||
dlg.setMinimumWidth(400);
|
|
||||||
|
|
||||||
QLineEdit *titleEdit = new QLineEdit(&dlg);
|
|
||||||
QTextEdit *descEdit = new QTextEdit(&dlg);
|
|
||||||
QLineEdit *authorEdit = new QLineEdit(&dlg);
|
|
||||||
QSpinBox *timeLimitSpin = new QSpinBox(&dlg);
|
|
||||||
QCheckBox *publishedCheck = new QCheckBox("Опубликован", &dlg);
|
|
||||||
|
|
||||||
descEdit->setMaximumHeight(80);
|
|
||||||
timeLimitSpin->setRange(1, 600);
|
|
||||||
timeLimitSpin->setValue(30);
|
|
||||||
timeLimitSpin->setSuffix(" мин");
|
|
||||||
|
|
||||||
{
|
|
||||||
auto *layout = new QVBoxLayout();
|
|
||||||
auto *form = new QFormLayout();
|
|
||||||
form->addRow("Название:", titleEdit);
|
|
||||||
form->addRow("Описание:", descEdit);
|
|
||||||
form->addRow("Автор:", authorEdit);
|
|
||||||
form->addRow("Время:", timeLimitSpin);
|
|
||||||
form->addRow("", publishedCheck);
|
|
||||||
layout->addLayout(form);
|
|
||||||
auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
|
||||||
connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
|
|
||||||
connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
|
|
||||||
layout->addWidget(buttons);
|
|
||||||
dlg.setLayout(layout);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dlg.exec() != QDialog::Accepted) return;
|
|
||||||
|
|
||||||
QJsonObject data;
|
|
||||||
data["title"] = titleEdit->text();
|
|
||||||
data["description"] = descEdit->toPlainText();
|
|
||||||
data["author"] = authorEdit->text();
|
|
||||||
data["time_limit"] = timeLimitSpin->value();
|
|
||||||
data["is_published"] = publishedCheck->isChecked();
|
|
||||||
|
|
||||||
++m_requestCount;
|
|
||||||
setStatus(QString("POST /api/quiz/… | Запросов: %1").arg(m_requestCount));
|
|
||||||
ApiClient::instance().createQuiz(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::on_btnUpdate_clicked()
|
|
||||||
{
|
|
||||||
bool ok;
|
|
||||||
int id = QInputDialog::getInt(this, "Update Quiz", "ID теста для обновления:", 1, 1, 99999, 1, &ok);
|
|
||||||
if (!ok) return;
|
|
||||||
|
|
||||||
QDialog dlg(this);
|
|
||||||
dlg.setWindowTitle(QString("Обновить тест ID=%1 — PUT /api/quiz/%1/").arg(id));
|
|
||||||
dlg.setMinimumWidth(400);
|
|
||||||
|
|
||||||
QLineEdit *titleEdit = new QLineEdit(&dlg);
|
|
||||||
QTextEdit *descEdit = new QTextEdit(&dlg);
|
|
||||||
QLineEdit *authorEdit = new QLineEdit(&dlg);
|
|
||||||
QSpinBox *timeLimitSpin = new QSpinBox(&dlg);
|
|
||||||
QCheckBox *publishedCheck = new QCheckBox("Опубликован", &dlg);
|
|
||||||
|
|
||||||
descEdit->setMaximumHeight(80);
|
|
||||||
timeLimitSpin->setRange(1, 600);
|
|
||||||
timeLimitSpin->setValue(30);
|
|
||||||
timeLimitSpin->setSuffix(" мин");
|
|
||||||
|
|
||||||
{
|
|
||||||
auto *layout = new QVBoxLayout();
|
|
||||||
auto *form = new QFormLayout();
|
|
||||||
form->addRow("Название:", titleEdit);
|
|
||||||
form->addRow("Описание:", descEdit);
|
|
||||||
form->addRow("Автор:", authorEdit);
|
|
||||||
form->addRow("Время:", timeLimitSpin);
|
|
||||||
form->addRow("", publishedCheck);
|
|
||||||
layout->addLayout(form);
|
|
||||||
auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
|
||||||
connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
|
|
||||||
connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
|
|
||||||
layout->addWidget(buttons);
|
|
||||||
dlg.setLayout(layout);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dlg.exec() != QDialog::Accepted) return;
|
|
||||||
|
|
||||||
QJsonObject data;
|
|
||||||
data["title"] = titleEdit->text();
|
|
||||||
data["description"] = descEdit->toPlainText();
|
|
||||||
data["author"] = authorEdit->text();
|
|
||||||
data["time_limit"] = timeLimitSpin->value();
|
|
||||||
data["is_published"] = publishedCheck->isChecked();
|
|
||||||
|
|
||||||
++m_requestCount;
|
|
||||||
setStatus(QString("PUT /api/quiz/%1/… | Запросов: %2").arg(id).arg(m_requestCount));
|
|
||||||
ApiClient::instance().updateQuiz(id, data);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::on_btnDelete_clicked()
|
|
||||||
{
|
|
||||||
bool ok;
|
|
||||||
int id = QInputDialog::getInt(this, "Delete Quiz", "ID теста для удаления:", 1, 1, 99999, 1, &ok);
|
|
||||||
if (!ok) return;
|
|
||||||
++m_requestCount;
|
|
||||||
setStatus(QString("DELETE /api/quiz/%1/… | Запросов: %2").arg(id).arg(m_requestCount));
|
|
||||||
ApiClient::instance().deleteQuiz(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::on_btnClear_clicked()
|
|
||||||
{
|
|
||||||
ui->tableWidget->setRowCount(0);
|
|
||||||
ui->outputEdit->clear();
|
|
||||||
ui->lblStatus->setText("<b>Результат:</b>");
|
|
||||||
setStatus("Очищено");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Слоты ответов ApiClient ───────────────────────────────────────────────────
|
|
||||||
void MainWindow::onQuizzesReceived(const QList<Quiz> &quizzes)
|
|
||||||
{
|
|
||||||
showQuizzes(quizzes);
|
|
||||||
|
|
||||||
ui->outputEdit->clear();
|
|
||||||
ui->outputEdit->append(QString("<b>Тестов получено: %1</b>").arg(quizzes.size()));
|
|
||||||
for (const Quiz &q : quizzes) {
|
|
||||||
ui->outputEdit->append("─────────────────────────────");
|
|
||||||
appendQuizText(q);
|
|
||||||
}
|
|
||||||
|
|
||||||
ui->lblStatus->setText(QString("<b>Результат:</b> получено тестов: <b>%1</b>").arg(quizzes.size()));
|
|
||||||
setStatus(QString("Готово — получено %1 тестов | Запросов: %2").arg(quizzes.size()).arg(m_requestCount));
|
|
||||||
qDebug() << "[GET ALL] count:" << quizzes.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onQuizReceived(const Quiz &q)
|
|
||||||
{
|
|
||||||
showSingleQuiz(q, "GET");
|
|
||||||
|
|
||||||
ui->outputEdit->clear();
|
|
||||||
ui->outputEdit->append("<b>GET — тест по ID</b>");
|
|
||||||
ui->outputEdit->append("─────────────────────────────");
|
|
||||||
appendQuizText(q);
|
|
||||||
|
|
||||||
ui->lblStatus->setText(QString("<b>Результат:</b> тест ID=<b>%1</b>").arg(q.id));
|
|
||||||
setStatus(QString("Готово — тест ID=%1 | Запросов: %2").arg(q.id).arg(m_requestCount));
|
|
||||||
qDebug() << "[GET] ID:" << q.id << q.title;
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onQuizCreated(const Quiz &q)
|
|
||||||
{
|
|
||||||
showSingleQuiz(q, "POST");
|
|
||||||
|
|
||||||
ui->outputEdit->clear();
|
|
||||||
ui->outputEdit->append("<b>POST — тест создан</b>");
|
|
||||||
ui->outputEdit->append("─────────────────────────────");
|
|
||||||
appendQuizText(q);
|
|
||||||
|
|
||||||
ui->lblStatus->setText(QString("<b>Результат:</b> тест создан, ID=<b>%1</b>").arg(q.id));
|
|
||||||
setStatus(QString("Тест создан, ID=%1 | Запросов: %2").arg(q.id).arg(m_requestCount));
|
|
||||||
qDebug() << "[CREATE] ID:" << q.id << q.title;
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onQuizUpdated(const Quiz &q)
|
|
||||||
{
|
|
||||||
showSingleQuiz(q, "PUT");
|
|
||||||
|
|
||||||
ui->outputEdit->clear();
|
|
||||||
ui->outputEdit->append("<b>PUT — тест обновлён</b>");
|
|
||||||
ui->outputEdit->append("─────────────────────────────");
|
|
||||||
appendQuizText(q);
|
|
||||||
|
|
||||||
ui->lblStatus->setText(QString("<b>Результат:</b> тест обновлён, ID=<b>%1</b>").arg(q.id));
|
|
||||||
setStatus(QString("Тест обновлён, ID=%1 | Запросов: %2").arg(q.id).arg(m_requestCount));
|
|
||||||
qDebug() << "[UPDATE] ID:" << q.id << q.title;
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onQuizDeleted(const QString &message)
|
|
||||||
{
|
|
||||||
ui->tableWidget->setRowCount(0);
|
|
||||||
ui->outputEdit->clear();
|
|
||||||
ui->outputEdit->append("<b>DELETE — успешно</b>");
|
|
||||||
ui->outputEdit->append(message);
|
|
||||||
|
|
||||||
ui->lblStatus->setText(QString("<b>Результат:</b> <span style='color:#4ade80'>%1</span>").arg(message));
|
|
||||||
setStatus(QString("Тест удалён | Запросов: %1").arg(m_requestCount));
|
|
||||||
qDebug() << "[DELETE]" << message;
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onError(const QString &error)
|
|
||||||
{
|
|
||||||
ui->outputEdit->append(
|
|
||||||
QString("<span style='color:#f87171'><b>Ошибка:</b> %1</span>").arg(error));
|
|
||||||
ui->lblStatus->setText(QString("<b>Результат:</b> <span style='color:#f87171'>Ошибка: %1</span>").arg(error));
|
|
||||||
setStatus(QString("Ошибка | Запросов: %1").arg(m_requestCount));
|
|
||||||
qDebug() << "[ERROR]" << error;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Вспомогательные методы ────────────────────────────────────────────────────
|
|
||||||
void MainWindow::showQuizzes(const QList<Quiz> &quizzes)
|
|
||||||
{
|
|
||||||
ui->tableWidget->setRowCount(0);
|
|
||||||
ui->tableWidget->setRowCount(quizzes.size());
|
|
||||||
|
|
||||||
for (int i = 0; i < quizzes.size(); ++i) {
|
|
||||||
const Quiz &q = quizzes[i];
|
|
||||||
|
|
||||||
QColor rowColor = q.isPublished ? QColor("#052e16") : QColor("#1f2937");
|
|
||||||
|
|
||||||
auto makeItem = [&](const QString &text) {
|
|
||||||
auto *item = new QTableWidgetItem(text);
|
|
||||||
item->setBackground(rowColor);
|
|
||||||
item->setForeground(QColor("#f9fafb"));
|
|
||||||
item->setTextAlignment(Qt::AlignCenter);
|
|
||||||
return item;
|
|
||||||
};
|
|
||||||
|
|
||||||
ui->tableWidget->setItem(i, COL_ID, makeItem(QString::number(q.id)));
|
|
||||||
ui->tableWidget->setItem(i, COL_TITLE, makeItem(q.title));
|
|
||||||
ui->tableWidget->setItem(i, COL_AUTHOR, makeItem(q.author));
|
|
||||||
ui->tableWidget->setItem(i, COL_TIME, makeItem(QString::number(q.timeLimit)));
|
|
||||||
ui->tableWidget->setItem(i, COL_DESCRIPTION, makeItem(q.description));
|
|
||||||
ui->tableWidget->setItem(i, COL_CREATED, makeItem(q.createdAt.toString("dd.MM.yyyy")));
|
|
||||||
|
|
||||||
auto *pubItem = new QTableWidgetItem(q.isPublished ? "Да" : "Нет");
|
|
||||||
pubItem->setBackground(rowColor);
|
|
||||||
pubItem->setForeground(q.isPublished ? QColor("#4ade80") : QColor("#9ca3af"));
|
|
||||||
pubItem->setTextAlignment(Qt::AlignCenter);
|
|
||||||
QFont f = pubItem->font();
|
|
||||||
f.setBold(true);
|
|
||||||
pubItem->setFont(f);
|
|
||||||
ui->tableWidget->setItem(i, COL_PUBLISHED, pubItem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::showSingleQuiz(const Quiz &q, const QString &operation)
|
|
||||||
{
|
|
||||||
ui->tableWidget->setRowCount(1);
|
|
||||||
|
|
||||||
QColor rowColor = QColor("#1f2937");
|
|
||||||
if (operation == "POST") rowColor = QColor("#052e16");
|
|
||||||
else if (operation == "PUT") rowColor = QColor("#422006");
|
|
||||||
|
|
||||||
auto makeItem = [&](const QString &text) {
|
|
||||||
auto *item = new QTableWidgetItem(text);
|
|
||||||
item->setBackground(rowColor);
|
|
||||||
item->setForeground(QColor("#f9fafb"));
|
|
||||||
item->setTextAlignment(Qt::AlignCenter);
|
|
||||||
return item;
|
|
||||||
};
|
|
||||||
|
|
||||||
ui->tableWidget->setItem(0, COL_ID, makeItem(QString::number(q.id)));
|
|
||||||
ui->tableWidget->setItem(0, COL_TITLE, makeItem(q.title));
|
|
||||||
ui->tableWidget->setItem(0, COL_AUTHOR, makeItem(q.author));
|
|
||||||
ui->tableWidget->setItem(0, COL_TIME, makeItem(QString::number(q.timeLimit)));
|
|
||||||
ui->tableWidget->setItem(0, COL_DESCRIPTION, makeItem(q.description));
|
|
||||||
ui->tableWidget->setItem(0, COL_CREATED, makeItem(q.createdAt.toString("dd.MM.yyyy")));
|
|
||||||
|
|
||||||
auto *pubItem = new QTableWidgetItem(q.isPublished ? "Да" : "Нет");
|
|
||||||
pubItem->setBackground(rowColor);
|
|
||||||
pubItem->setForeground(q.isPublished ? QColor("#4ade80") : QColor("#9ca3af"));
|
|
||||||
pubItem->setTextAlignment(Qt::AlignCenter);
|
|
||||||
QFont f = pubItem->font();
|
|
||||||
f.setBold(true);
|
|
||||||
pubItem->setFont(f);
|
|
||||||
ui->tableWidget->setItem(0, COL_PUBLISHED, pubItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::appendQuizText(const Quiz &q)
|
|
||||||
{
|
|
||||||
ui->outputEdit->append(QString(
|
|
||||||
"ID: %1\n"
|
|
||||||
"Название: %2\n"
|
|
||||||
"Описание: %3\n"
|
|
||||||
"Автор: %4\n"
|
|
||||||
"Создан: %5\n"
|
|
||||||
"Время (мин): %6\n"
|
|
||||||
"Опубликован: %7"
|
|
||||||
).arg(q.id)
|
|
||||||
.arg(q.title)
|
|
||||||
.arg(q.description)
|
|
||||||
.arg(q.author)
|
|
||||||
.arg(q.createdAt.toString(Qt::ISODate))
|
|
||||||
.arg(q.timeLimit)
|
|
||||||
.arg(q.isPublished ? "Да" : "Нет"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::setStatus(const QString &msg)
|
|
||||||
{
|
|
||||||
statusBar()->showMessage(msg);
|
|
||||||
}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
#ifndef MAINWINDOW_H
|
|
||||||
#define MAINWINDOW_H
|
|
||||||
|
|
||||||
#include <QMainWindow>
|
|
||||||
#include <QList>
|
|
||||||
#include "quiz.h"
|
|
||||||
|
|
||||||
QT_BEGIN_NAMESPACE
|
|
||||||
namespace Ui { class MainWindow; }
|
|
||||||
QT_END_NAMESPACE
|
|
||||||
|
|
||||||
class MainWindow : public QMainWindow
|
|
||||||
{
|
|
||||||
Q_OBJECT
|
|
||||||
|
|
||||||
public:
|
|
||||||
explicit MainWindow(QWidget *parent = nullptr);
|
|
||||||
~MainWindow() override;
|
|
||||||
|
|
||||||
private slots:
|
|
||||||
void on_btnGetAll_clicked();
|
|
||||||
void on_btnGetById_clicked();
|
|
||||||
void on_btnCreate_clicked();
|
|
||||||
void on_btnUpdate_clicked();
|
|
||||||
void on_btnDelete_clicked();
|
|
||||||
void on_btnClear_clicked();
|
|
||||||
|
|
||||||
void onQuizzesReceived(const QList<Quiz> &quizzes);
|
|
||||||
void onQuizReceived(const Quiz &quiz);
|
|
||||||
void onQuizCreated(const Quiz &quiz);
|
|
||||||
void onQuizUpdated(const Quiz &quiz);
|
|
||||||
void onQuizDeleted(const QString &message);
|
|
||||||
void onError(const QString &error);
|
|
||||||
|
|
||||||
private:
|
|
||||||
void setupTable();
|
|
||||||
void showQuizzes(const QList<Quiz> &quizzes);
|
|
||||||
void showSingleQuiz(const Quiz &q, const QString &operation);
|
|
||||||
void appendQuizText(const Quiz &q);
|
|
||||||
void setStatus(const QString &msg);
|
|
||||||
|
|
||||||
Ui::MainWindow *ui;
|
|
||||||
int m_requestCount = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // MAINWINDOW_H
|
|
||||||
|
|
@ -1,157 +0,0 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<ui version="4.0">
|
|
||||||
<class>MainWindow</class>
|
|
||||||
<widget class="QMainWindow" name="MainWindow">
|
|
||||||
<property name="geometry">
|
|
||||||
<rect>
|
|
||||||
<x>0</x>
|
|
||||||
<y>0</y>
|
|
||||||
<width>1000</width>
|
|
||||||
<height>620</height>
|
|
||||||
</rect>
|
|
||||||
</property>
|
|
||||||
<property name="windowTitle">
|
|
||||||
<string>Quiz Client — ЛР3</string>
|
|
||||||
</property>
|
|
||||||
<widget class="QWidget" name="centralwidget">
|
|
||||||
<layout class="QVBoxLayout" name="verticalLayout">
|
|
||||||
<property name="spacing">
|
|
||||||
<number>8</number>
|
|
||||||
</property>
|
|
||||||
<item>
|
|
||||||
<layout class="QHBoxLayout" name="buttonLayout">
|
|
||||||
<property name="spacing">
|
|
||||||
<number>6</number>
|
|
||||||
</property>
|
|
||||||
<item>
|
|
||||||
<widget class="QPushButton" name="btnGetAll">
|
|
||||||
<property name="minimumSize"><size><width>0</width><height>48</height></size></property>
|
|
||||||
<property name="text"><string>Все тесты
|
|
||||||
GET /api/quiz/</string></property>
|
|
||||||
<property name="styleSheet"><string>QPushButton { background:#2d4a6b; color:#bfdbfe; border-radius:6px; font-weight:bold; border:1px solid #3b5f8a; }
|
|
||||||
QPushButton:hover { background:#3b5f8a; }</string></property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item>
|
|
||||||
<widget class="QPushButton" name="btnGetById">
|
|
||||||
<property name="minimumSize"><size><width>0</width><height>48</height></size></property>
|
|
||||||
<property name="text"><string>По ID
|
|
||||||
GET /api/quiz/:id/</string></property>
|
|
||||||
<property name="styleSheet"><string>QPushButton { background:#2d4a6b; color:#bfdbfe; border-radius:6px; font-weight:bold; border:1px solid #3b5f8a; }
|
|
||||||
QPushButton:hover { background:#3b5f8a; }</string></property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item>
|
|
||||||
<widget class="QPushButton" name="btnCreate">
|
|
||||||
<property name="minimumSize"><size><width>0</width><height>48</height></size></property>
|
|
||||||
<property name="text"><string>Создать
|
|
||||||
POST /api/quiz/</string></property>
|
|
||||||
<property name="styleSheet"><string>QPushButton { background:#1a3d2b; color:#86efac; border-radius:6px; font-weight:bold; border:1px solid #256040; }
|
|
||||||
QPushButton:hover { background:#256040; }</string></property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item>
|
|
||||||
<widget class="QPushButton" name="btnUpdate">
|
|
||||||
<property name="minimumSize"><size><width>0</width><height>48</height></size></property>
|
|
||||||
<property name="text"><string>Обновить
|
|
||||||
PUT /api/quiz/:id/</string></property>
|
|
||||||
<property name="styleSheet"><string>QPushButton { background:#3d2e0a; color:#fcd34d; border-radius:6px; font-weight:bold; border:1px solid #5a4210; }
|
|
||||||
QPushButton:hover { background:#5a4210; }</string></property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item>
|
|
||||||
<widget class="QPushButton" name="btnDelete">
|
|
||||||
<property name="minimumSize"><size><width>0</width><height>48</height></size></property>
|
|
||||||
<property name="text"><string>Удалить
|
|
||||||
DELETE /api/quiz/:id/</string></property>
|
|
||||||
<property name="styleSheet"><string>QPushButton { background:#4a1a1a; color:#fca5a5; border-radius:6px; font-weight:bold; border:1px solid #6b2424; }
|
|
||||||
QPushButton:hover { background:#6b2424; }</string></property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item>
|
|
||||||
<widget class="QPushButton" name="btnClear">
|
|
||||||
<property name="minimumSize"><size><width>0</width><height>48</height></size></property>
|
|
||||||
<property name="text"><string>Очистить</string></property>
|
|
||||||
<property name="styleSheet"><string>QPushButton { background:#2d3748; color:#9ca3af; border-radius:6px; border:1px solid #4b5563; font-weight:bold; }
|
|
||||||
QPushButton:hover { background:#374151; }</string></property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
</layout>
|
|
||||||
</item>
|
|
||||||
<item>
|
|
||||||
<widget class="QLabel" name="lblStatus">
|
|
||||||
<property name="text"><string><b>Результат:</b></string></property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item>
|
|
||||||
<widget class="QTabWidget" name="tabWidget">
|
|
||||||
<property name="currentIndex"><number>0</number></property>
|
|
||||||
<property name="tabPosition"><enum>QTabWidget::TabPosition::North</enum></property>
|
|
||||||
<property name="tabBarAutoHide"><bool>false</bool></property>
|
|
||||||
<property name="styleSheet"><string>QTabWidget::pane { border: 1px solid #374151; border-radius: 0 4px 4px 4px; }
|
|
||||||
QTabBar::tab { background:#1f2937; color:#9ca3af; padding:6px 20px; border: 1px solid #374151; border-bottom: none; border-radius: 4px 4px 0 0; font-weight:bold; }
|
|
||||||
QTabBar::tab:selected { background:#111827; color:#f9fafb; border-color:#4b5563; }
|
|
||||||
QTabBar::tab:hover { background:#374151; color:#e5e7eb; }</string></property>
|
|
||||||
<widget class="QWidget" name="pageTable">
|
|
||||||
<attribute name="title"><string>Таблица</string></attribute>
|
|
||||||
<layout class="QVBoxLayout" name="pageTableLayout">
|
|
||||||
<property name="spacing"><number>0</number></property>
|
|
||||||
<property name="leftMargin"><number>0</number></property>
|
|
||||||
<property name="topMargin"><number>0</number></property>
|
|
||||||
<property name="rightMargin"><number>0</number></property>
|
|
||||||
<property name="bottomMargin"><number>0</number></property>
|
|
||||||
<item>
|
|
||||||
<widget class="QTableWidget" name="tableWidget">
|
|
||||||
<property name="selectionBehavior"><enum>QAbstractItemView::SelectionBehavior::SelectRows</enum></property>
|
|
||||||
<property name="selectionMode"><enum>QAbstractItemView::SelectionMode::SingleSelection</enum></property>
|
|
||||||
<property name="editTriggers"><set>QAbstractItemView::EditTrigger::NoEditTriggers</set></property>
|
|
||||||
<property name="wordWrap"><bool>true</bool></property>
|
|
||||||
<property name="styleSheet"><string>QTableWidget { gridline-color: #374151; border: none; color: #f9fafb; background: #111827; alternate-background-color: #1f2937; }
|
|
||||||
QHeaderView::section { background: #1f2937; color: #e5e7eb; font-weight: bold; padding: 6px 4px; border: none; border-bottom: 2px solid #4b5563; border-right: 1px solid #374151; }
|
|
||||||
QScrollBar:vertical { background: #1f2937; width: 10px; border-radius: 5px; }
|
|
||||||
QScrollBar::handle:vertical { background: #4b5563; border-radius: 5px; min-height: 20px; }
|
|
||||||
QScrollBar::handle:vertical:hover { background: #6b7280; }
|
|
||||||
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0px; }
|
|
||||||
QScrollBar:horizontal { background: #1f2937; height: 10px; border-radius: 5px; }
|
|
||||||
QScrollBar::handle:horizontal { background: #4b5563; border-radius: 5px; min-width: 20px; }
|
|
||||||
QScrollBar::handle:horizontal:hover { background: #6b7280; }
|
|
||||||
QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal { width: 0px; }</string></property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
</layout>
|
|
||||||
</widget>
|
|
||||||
<widget class="QWidget" name="pageText">
|
|
||||||
<attribute name="title"><string>Текст</string></attribute>
|
|
||||||
<layout class="QVBoxLayout" name="pageTextLayout">
|
|
||||||
<property name="spacing"><number>0</number></property>
|
|
||||||
<property name="leftMargin"><number>0</number></property>
|
|
||||||
<property name="topMargin"><number>0</number></property>
|
|
||||||
<property name="rightMargin"><number>0</number></property>
|
|
||||||
<property name="bottomMargin"><number>0</number></property>
|
|
||||||
<item>
|
|
||||||
<widget class="QTextEdit" name="outputEdit">
|
|
||||||
<property name="readOnly"><bool>true</bool></property>
|
|
||||||
<property name="font">
|
|
||||||
<font>
|
|
||||||
<family>Courier New</family>
|
|
||||||
<pointsize>10</pointsize>
|
|
||||||
</font>
|
|
||||||
</property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
</layout>
|
|
||||||
</widget>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
</layout>
|
|
||||||
</widget>
|
|
||||||
<widget class="QMenuBar" name="menubar">
|
|
||||||
<property name="geometry">
|
|
||||||
<rect><x>0</x><y>0</y><width>1000</width><height>21</height></rect>
|
|
||||||
</property>
|
|
||||||
</widget>
|
|
||||||
<widget class="QStatusBar" name="statusbar"/>
|
|
||||||
</widget>
|
|
||||||
<resources/>
|
|
||||||
<connections/>
|
|
||||||
</ui>
|
|
||||||
20
lab-3/quiz.h
20
lab-3/quiz.h
|
|
@ -1,20 +0,0 @@
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <QString>
|
|
||||||
#include <QDateTime>
|
|
||||||
|
|
||||||
class Quiz
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
Quiz() = default;
|
|
||||||
|
|
||||||
int id = 0;
|
|
||||||
|
|
||||||
QString title;
|
|
||||||
QString description;
|
|
||||||
QString author;
|
|
||||||
QDateTime createdAt;
|
|
||||||
|
|
||||||
int timeLimit = 0;
|
|
||||||
bool isPublished = false;
|
|
||||||
};
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
#include "quiz_json_adapter.h"
|
|
||||||
#include <QJsonValue>
|
|
||||||
|
|
||||||
// toQuiz — десериализация одного объекта
|
|
||||||
Quiz QuizJsonAdapter::toQuiz(const QJsonObject &json) const
|
|
||||||
{
|
|
||||||
Quiz q;
|
|
||||||
|
|
||||||
q.id = json["id"].toInt();
|
|
||||||
|
|
||||||
q.title = json["title"].toString();
|
|
||||||
q.description = json["description"].toString();
|
|
||||||
q.author = json["author"].toString();
|
|
||||||
|
|
||||||
q.createdAt = QDateTime::fromString(json["created_at"].toString(),
|
|
||||||
Qt::ISODateWithMs);
|
|
||||||
|
|
||||||
q.timeLimit = json["time_limit"].toInt();
|
|
||||||
|
|
||||||
q.isPublished = json["is_published"].toBool();
|
|
||||||
|
|
||||||
return q;
|
|
||||||
}
|
|
||||||
|
|
||||||
// toQuizList — десериализация массива объектов
|
|
||||||
QList<Quiz> QuizJsonAdapter::toQuizList(const QJsonArray &json) const
|
|
||||||
{
|
|
||||||
QList<Quiz> list;
|
|
||||||
|
|
||||||
list.reserve(json.size());
|
|
||||||
|
|
||||||
for (const QJsonValue &value : json) {
|
|
||||||
if (value.isObject()) {
|
|
||||||
list.append(toQuiz(value.toObject()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return list;
|
|
||||||
}
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include "iquiz_adapter.h"
|
|
||||||
|
|
||||||
class QuizJsonAdapter : public IQuizAdapter
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
Quiz toQuiz (const QJsonObject &json) const override;
|
|
||||||
QList<Quiz> toQuizList(const QJsonArray &json) const override;
|
|
||||||
};
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
<RCC>
|
|
||||||
<qresource prefix="/">
|
|
||||||
<file>icons/app.svg</file>
|
|
||||||
</qresource>
|
|
||||||
</RCC>
|
|
||||||
Loading…
Add table
Reference in a new issue