Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Qt / Лабораторная №1

.doc
Скачиваний:
2
Добавлен:
27.11.2023
Размер:
368.13 Кб
Скачать

Цель работы: создать программу To Do List.

Ход работы

Программа разработана на платформе Qt

Qt — фреймворк для разработки кроссплатформенного программного обеспечения на языке программирования C++.

Листинг программы:

Файл main.cpp

#include "tdlmainwindow.h"

#include <QtWidgets/QApplication>

int main(int argc, char* argv[])

{

QApplication a(argc, argv);

QApplication::setOrganizationName("GP");

QApplication::setApplicationName("ToDoList");

TDLMainWindow w;

w.show();

return a.exec();

}

Файл tdlmainwindow_h

#ifndef TDLMAINWINDOW_H

#define TDLMAINWINDOW_H

#pragma once

#include <QtWidgets/QMainWindow>

#include <QtCore> //классы ядра библиотеки, используемые другими модулями;

#include <QtGui> //компоненты графического интерфейса

#include <QSettings> //https://www.youtube.com/watch?v=n1t6qogQx4Q

#include <QListView>

#include <QListWidget>

#include <QHBoxLayout>

#include <QVBoxLayout>

#include <QStringListModel>

#include <QToolBar>

#include <QMessageBox>

namespace Ui { class TDLMainWindow; }

class TDLMainWindow : public QMainWindow

{

Q_OBJECT

public:

TDLMainWindow(QWidget* parent = nullptr);

~TDLMainWindow();

private slots:

void onAdd();

void onRemove();

private:

Ui::TDLMainWindow* ui;

QStringListModel* model_1 = nullptr; //Класс QStringListModel предоставляет модель, которая предоставляет строки

QStringListModel* model_2 = nullptr;

QSettings* settings;

QAction* m_pActAdd = nullptr;

QAction* m_pActRemove = nullptr;

};

#endif // TDLMAINWINDOW_H

Файл tdlmainwindow.cpp

#include "tdlmainwindow.h"

#include "ui_TDLWindow.h"

TDLMainWindow::TDLMainWindow(QWidget* parent)

: QMainWindow(parent)

, ui(new Ui::TDLMainWindow)

{

QSettings s; //востановления геометрии окна

restoreGeometry(s.value("ToDoList", QByteArray()).toByteArray());

restoreState(s.value("GP", QByteArray()).toByteArray());

ui->setupUi(this);

//////////////// Лист_1 Drag&Drop

model_1 = new QStringListModel(this);

QStringList stringList_1;

ui->listView->setModel(model_1); // Склеиваем модель и вид вместе

ui->listView->setEditTriggers(QAbstractItemView::AnyKeyPressed | QAbstractItemView::DoubleClicked); //добавление дополнительных функциий в список.

ui->listView->setDragDropMode(QAbstractItemView::DragDrop); //вкл функции DragDrop

ui->listView->setDefaultDropAction(Qt::MoveAction); //действие по умолчанию

ui->listView->setDragEnabled(true);

ui->listView->setAcceptDrops(true);

// открытие файла

QFile textFile(":/resources/Data.txt");

if (!textFile.open(QIODevice::ReadOnly)) {

QMessageBox::information(0, "Error", textFile.errorString());

}

// тестовый поток для чтения из файла

QTextStream textStream(&textFile);

while (true)

{

QString line = textStream.readLine();

if (line.isNull())

break;

else

stringList_1.append(line);

}

// Заполняем модель

model_1->setStringList(stringList_1);

//////////////// Лист_2 Drag&Drop

model_2 = new QStringListModel(this);

ui->listView_2->setModel(model_2);

ui->listView_2->setEditTriggers(QAbstractItemView::AnyKeyPressed | QAbstractItemView::DoubleClicked); //добавление дополнительных функциий в список.

ui->listView_2->setDragDropMode(QAbstractItemView::DragDrop);

ui->listView_2->setDefaultDropAction(Qt::MoveAction);

ui->listView_2->setDragEnabled(true);

ui->listView_2->setAcceptDrops(true);

/////////////////Панель инструментов (нет в форме "TDLWindow")

QToolBar* pToolBar = new QToolBar(this);

addToolBar(pToolBar);

m_pActAdd = new QAction(this);

m_pActAdd->setIcon(QIcon(":/resources/add.png"));

connect(m_pActAdd, &QAction::triggered, this, &TDLMainWindow::onAdd);

m_pActRemove = new QAction(this);

m_pActRemove->setIcon(QIcon(":/resources/remove.png"));

connect(m_pActRemove, &QAction::triggered, this, &TDLMainWindow::onRemove);

pToolBar->addAction(m_pActAdd);

pToolBar->addAction(m_pActRemove);

}

void TDLMainWindow::onAdd()

{

int row = model_1->rowCount();

model_1->insertRows(row, 1);

QModelIndex index = model_1->index(row);

ui->listView->setCurrentIndex(index);

ui->listView->edit(index);

}

void TDLMainWindow::onRemove()

{

model_1->removeRows(ui->listView->currentIndex().row(), 1);

}

TDLMainWindow::~TDLMainWindow()

{

QSettings s; //запись геометрии окна после закрытия

s.setValue("GP", saveState());

s.setValue("ToDoList", saveGeometry());

delete ui;

}

Интерфейс программы To Do List:

Вывод: в ходе лабораторной работы разработали программу с пользовательским интерфейсом To Do List.

Соседние файлы в папке Qt