Advertisement
Guest User

Untitled

a guest
May 13th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include "texteditor.h"
  2. #include "ui_texteditor.h"
  3. #include <QDebug>
  4.  
  5. TextEditor::TextEditor(QWidget *parent) :
  6.     QMainWindow(parent),
  7.     ui(new Ui::TextEditor)
  8. {
  9.     ui->setupUi(this);
  10.     ui->all_save->setEnabled(false);
  11.     configElements(false);
  12. }
  13.  
  14. TextEditor::~TextEditor()
  15. {
  16.     delete ui;
  17. }
  18.  
  19. // Открытия файлы
  20. void TextEditor::on_openFileButton_clicked()
  21. {
  22.     // Получаем имя файла для открытия: открывается диалоговое окно, которое разрешает выбрать только текстовые (txt) файлы
  23.     QString filename = QFileDialog::getOpenFileName(this, tr("Выберите файл"), QDir::currentPath(), tr("Text files (*.txt)"));
  24.  
  25.     // Проверка, если мы выбрали какой-либо файл, или его название (т.е название - длина не равна нулю)
  26.     if (QString::compare(filename, QString()) != 0) {
  27.  
  28.         // Создаем файл файла
  29.         QFile textFile(filename);
  30.  
  31.         // Открытие файла (проверка на возможность что-то считать оттуда)
  32.         if (!textFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
  33.             qDebug() << "Ошибка открытия файла";
  34.             return;
  35.         }
  36.         textFileName  = filename;
  37.  
  38.         // Файл открылся, происходит построчное считывание
  39.         // counter - счетчик строк (записей)
  40.         int counter = 0;
  41.         QTextStream textStream(&textFile);
  42.         while (!textStream.atEnd()) {
  43.             counter++;
  44.             linesStringList << textStream.readLine();
  45.         }
  46.         textFile.close();
  47.  
  48.         // В переменные записываем, сколько всего строк
  49.         // и говорим, что текущая строка == 1 (мы находимся на первой строке)
  50.         countLines = counter;
  51.         currentLine = 1;
  52.         ui->count_lines->setText("Студентов в базе данных: " + QString::number(countLines));
  53.         ui->current_line->setText("Текущий студент: " + QString::number(currentLine));
  54.  
  55.         // Вызываем функцию, которая делает доступным нажатие элекментов (после того как загрузился файл)
  56.         configElements(true);
  57.         on_read_first_line_clicked();
  58.      }
  59. }
  60.  
  61. /////////////////////////////
  62. /// Чтение строк
  63.  
  64. // Чтение следующей строки
  65. void TextEditor::on_read_next_line_clicked()
  66. {
  67.     if (currentLine == linesStringList.count()) {
  68.         QMessageBox messageBox;
  69.         messageBox.critical(0,"Ошибка!","Следующей записи нет. \nВы находитесь в конце.");
  70.         messageBox.setFixedSize(500,200);
  71.         return;
  72.     }
  73.  
  74.     currentLine += 1;
  75.     showLine(currentLine);
  76. }
  77.  
  78. // Чтение предыдущей строки
  79. void TextEditor::on_read_prev_line_clicked()
  80. {
  81.     if (currentLine == 1) {
  82.         QMessageBox messageBox;
  83.         messageBox.critical(0,"Ошибка!","Предыдущей записи нет. \nВы находитесь в начале.");
  84.         messageBox.setFixedSize(500,200);
  85.         return;
  86.     }
  87.  
  88.     currentLine -= 1;
  89.     showLine(currentLine);
  90. }
  91.  
  92. // Чтение первой строки
  93. void TextEditor::on_read_first_line_clicked()
  94. {
  95.     currentLine = 1;
  96.     showLine(currentLine);
  97. }
  98.  
  99. // Чтение последней строки
  100. void TextEditor::on_read_last_line_clicked()
  101. {
  102.     currentLine = linesStringList.count();
  103.     showLine(currentLine);
  104. }
  105.  
  106. /////////////////////////////
  107. /// Изменение строк
  108. ///
  109. // Изменение строки
  110. void TextEditor::on_change_cur_line_clicked()
  111. {
  112.     // Изменение строки - делаю поля допустиимыми для редактирования
  113.     ui->firstname_lineEdit->setReadOnly(false);
  114.     ui->lastname_lineEdit->setReadOnly(false);
  115.     ui->group_lineEdit->setReadOnly(false);
  116.     ui->all_save->setEnabled(true);
  117. }
  118.  
  119. // Удаление текущей строки
  120. void TextEditor::on_delete_cur_line_clicked()
  121. {
  122.     showLine(currentLine - 1);
  123.     linesStringList.removeAt(currentLine - 1);
  124.     ui->count_lines->setText("Студентов в базе данных: " + QString::number(--countLines));
  125.  
  126.     QFile file(textFileName);
  127.     if (file.open(QIODevice::ReadWrite)) {
  128.         QTextStream stream(&file);
  129.         for (QStringList::Iterator it = linesStringList.begin(); it != linesStringList.end(); ++it)
  130.             stream << *it << "\n";
  131.     }
  132.     file.close();
  133. }
  134.  
  135. // Добавление нового студента
  136. void TextEditor::on_addStudentButton_clicked()
  137. {
  138.     // Если хоть одно поле не заполнено, показывается диалог с ошибкой
  139.     if (ui->nameLine->text().isEmpty() || ui->surnameLine->text().isEmpty() || ui->addCourseLine->text().isEmpty()) {
  140.         QMessageBox messageBox;
  141.         messageBox.critical(0,"Ошибка!","Заполните все поля");
  142.         messageBox.setFixedSize(500,200);
  143.         return;
  144.     }
  145.  
  146.     QString newStudent = ui->nameLine->text() + " " +
  147.             ui->surnameLine->text() + " - " +
  148.             ui->addCourseLine->text();
  149.     linesStringList.append(newStudent);
  150.     ui->count_lines->setText("Студентов в базе данных: " + QString::number(++countLines));
  151.     on_all_save_clicked();
  152. }
  153.  
  154. /////////////////////////////
  155. /// Остальные методы
  156. ///
  157. // Открыть полностью текст в отдельном окне
  158. void TextEditor::on_open_text_clicked()
  159. {
  160.     // Создание диалогового окна, куда поместится файлик с записями
  161.     QTextBrowser *browser = new QTextBrowser;
  162.     QString text;
  163.     for (QString string : linesStringList) {
  164.         text.append(string + "\n");
  165.     }
  166.     browser->setText(text);
  167.     browser->show();
  168. }
  169.  
  170. // Отображение записи
  171. void TextEditor::showLine(int number) {
  172.  
  173.     // В функцию приходит номер, который нужно отобразить
  174.     // По номеру (индексу) достаем из массива нужного студента.
  175.     // Методом split делим его запись на 3 строки (Иван Иванов Матан)
  176.     // Первые 2 строки - Имя Фамилия, Последняя строка - направление
  177.  
  178.     QStringList splitStrings = linesStringList[number - 1].split(" - ");
  179.     QStringList students = splitStrings[0].split(" ");
  180.  
  181.     // Здесь как раз и устанавливаются значения этих строк в окна
  182.     ui->firstname_lineEdit->setText(students[0]);
  183.     ui->lastname_lineEdit->setText(students[1]);
  184.     ui->group_lineEdit->setText(splitStrings[1]);
  185.     ui->current_line->setText("Текущий студент: " + QString::number(number));
  186.     disableTextField();
  187. }
  188.  
  189. // Сохранить все изменения
  190. void TextEditor::on_all_save_clicked()
  191. {
  192.     disableTextField();
  193.     linesStringList[currentLine - 1] =
  194.             ui->firstname_lineEdit->text() + " " +
  195.             ui->lastname_lineEdit->text() + " - " +
  196.             ui->group_lineEdit->text();
  197.  
  198.     QFile file(textFileName);
  199.     if (file.open(QIODevice::ReadWrite)) {
  200.         QTextStream stream(&file);
  201.  
  202.         for (QStringList::Iterator it = linesStringList.begin(); it != linesStringList.end(); ++it)
  203.             stream << *it << "\n";
  204.     }
  205.     file.close();
  206. }
  207.  
  208. // Выход из программы
  209. void TextEditor::on_exit_clicked()
  210. {
  211.     qApp->exit();
  212. }
  213.  
  214. void TextEditor::configElements(bool isActive)
  215. {
  216.     ui->read_next_line->setEnabled(isActive);
  217.     ui->read_prev_line->setEnabled(isActive);
  218.     ui->read_first_line->setEnabled(isActive);
  219.     ui->read_last_line->setEnabled(isActive);
  220.     ui->change_cur_line->setEnabled(isActive);
  221.     ui->delete_cur_line->setEnabled(isActive);
  222.     ui->addStudentButton->setEnabled(isActive);
  223.     ui->open_text->setEnabled(isActive);
  224.  
  225.     ui->nameLine->setReadOnly(!isActive);
  226.     ui->surnameLine->setReadOnly(!isActive);
  227.     ui->addCourseLine->setReadOnly(!isActive);
  228. }
  229.  
  230. void TextEditor::disableTextField() {
  231.     ui->firstname_lineEdit->setReadOnly(true);
  232.     ui->lastname_lineEdit->setReadOnly(true);
  233.     ui->group_lineEdit->setReadOnly(true);
  234.     ui->all_save->setEnabled(false);
  235. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement