Development/Tutorials/Saving and loading (ru): Difference between revisions

    From KDE TechBase
    (Только начал переводить, надеюсь завтра закончу)
     
    (Закончил перевод. Завтра перечитаю и исправлю ошибки.)
    Line 235: Line 235:
    ===Добавление действий===
    ===Добавление действий===


    The first thing we are going to do is provide the outward interface for the user so they can tell the application to load and save. Like with the <tt>quit</tt> action in tutorial 3, we will use <tt>KStandardActions</tt>. On lines 37 to 47 we add the actions in the same way as for the <tt>quit</tt> action. For each one, we connect it to the appropriate slot that we declared in the header file.
    Первое, что мы собираемся сделать, это предоставить пользователю интерфейс, что бы он мог сказать приложению "загрузить" и "сохранить". Как действие <tt>quit</tt> в уроке 3, мы будем использовать <tt>KStandardActions</tt>. На строках с 37 по 47 мы добавляем действия тем же путем, что и действие <tt>quit</tt>. Каждое из них мы соединяем с соответствующим слотом, который мы объявили в заголовочном файле.


    ===Creating a new document===
    ===Создание нового документа===


    The first function we create is the <tt>newFile()</tt> function.
    Первая функция, которую мы создали - <tt>newFile()</tt>.
    <code cppqt>
    <code cppqt>
    void MainWindow::newFile()
    void MainWindow::newFile()
    Line 247: Line 247:
    }
    }
    </code>
    </code>
    <tt>fileName.clear()</tt> sets the <tt>fileName</tt> QString to be empty to reflect the fact that this document does not yet have a presence on disc. <tt>textArea->clear()</tt> then clears the central text area using the same function that we connected the <tt>clear</tt> <tt>KAction</tt> to in tutorial 3.
    <tt>fileName.clear()</tt> очищает переменную <tt>fileName</tt> типа QString, что отражает тот факт, что этого документа еще нет на диске. <tt>textArea->clear()</tt> очищает область текста, используя функцию, которую мы подключили к <tt>clear</tt> <tt>KAction</tt> в уроке 3.


    ===Saving a file===
    ===Сохранение файла===


    ====saveFileAs(QString)====
    ====saveFileAs(QString)====


    Now we get onto our first file handling code. We're going to implement a function which will save the contents of the text area to the file name given as a parameter. KDE provides a class for safely saving a file called {{class|KSaveFile}} which is derived from Qt's {{qt|QFile}}.
    Теперь разберем наш первый обработчик. Мы собираемся реализовать функцию, которая сохраняет содержимое текстовой области в файл имя которого передается в функцию. KDE предоставляет класс для безопасного сохранения файла именуемый {{class|KSaveFile}}, который является производным от Qt'шного {{qt|QFile}}.


    The function's prototype is
    Прототип функции:
    <code cppqt>
    <code cppqt>
    void MainWindow::saveFileAs(const QString &outputFileName)
    void MainWindow::saveFileAs(const QString &outputFileName)
    </code>
    </code>


    We then create our <tt>KSaveFile</tt> object and open it with
    Мы создаем объект <tt>KSaveFile</tt> и открываем файл:
    <code cppqt>
    <code cppqt>
    KSaveFile file(outputFileName);
    KSaveFile file(outputFileName);
    Line 266: Line 266:
    </code>
    </code>


    Now that we have our file to write to, we need to format the text in the text area to a format which can be written to file. For this, we create a {{qt|QByteArray}} and fill it with the plain text version of whatever is in the text area:
    Теперь у нас есть файл для записи, нам нужно отформатировать текст в текстовой области в формат, который может быть записан в файл. Для этого, мы создаем {{qt|QByteArray}} и заполняем его обычным текстом из текстовой области:
    <code cppqt>
    <code cppqt>
    QByteArray outputByteArray;
    QByteArray outputByteArray;
    outputByteArray.append(textArea->toPlainText().toUtf8());
    outputByteArray.append(textArea->toPlainText().toUtf8());
    </code>
    </code>
    Now that we have our <tt>QByteArray</tt>, we use it to write to the file with <tt>KSaveFile::write()</tt>. If we were using a normal <tt>QFile</tt>, this would make the changes immediately. However, if a problem occurred partway through writing, the file would become corrupted. For this reason, <tt>KSaveFile</tt> works by first writing to a temporary file and then, when you call <tt>KSaveFile::finalize()</tt> the changes are made to the actual file.
    Теперь у нас есть <tt>QByteArray</tt>, запишем его в файл с помощью <tt>KSaveFile::write()</tt>. Если бы мы использовали <tt>QFile</tt>, он бы моментально сделал бы изменения в тексте. Однако, если возникнет проблемма посреди записи, файл будет поврежден. По этой причине <tt>KSaveFile</tt> сначала записывает временный файл, а потом, когда вы вызываете <tt>KSaveFile::finalize()</tt> изменения попадают в текущий файл.
    <code cppqt>
    <code cppqt>
    file.write(outputByteArray);
    file.write(outputByteArray);
    Line 277: Line 277:
    file.close();
    file.close();
    </code>
    </code>
    Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.
    Наконец, мы записываем в переменную <tt>MainWindow</tt> <tt>fileName</tt> имя файла в который только, что сохранили.
    <code cppqt>
    <code cppqt>
    fileName = outputFileName;
    fileName = outputFileName;
    Line 284: Line 284:
    ====saveFileAs()====
    ====saveFileAs()====


    This is the function that the <tt>saveAs</tt> slot is connected to. It simply calls the generic <tt>saveFileAs(QString)</tt> function and passes the file name returned by <tt>{{class|KFileDialog}}::[http://api.kde.org/4.0-api/kdelibs-apidocs/kio/html/classKFileDialog.html#8891356c249c5911e1ab15cc2739a89b getSaveFileName()]</tt>.
    Эта функция к которой подключек слот <tt>saveAs</tt>. Она просто вызывает <tt>saveFileAs(QString)</tt> и передает ей имя файла возвращенное <tt>{{class|KFileDialog}}::[http://api.kde.org/4.0-api/kdelibs-apidocs/kio/html/classKFileDialog.html#8891356c249c5911e1ab15cc2739a89b getSaveFileName()]</tt>.


    <code cppqt>
    <code cppqt>
    Line 293: Line 293:
    </code>
    </code>


    This is our first actual use of the KIO library. {{class|KFileDialog}} provides a number of static functions for displaying the common file dialog that is used by all KDE applications. Calling <tt>KFileDialog::getSaveFileName()</tt> will display a dialog where the user can select the name of the file to save to or choose a new name. The function returns the full file name, which we then pass to <tt>saveFileAs(QString)</tt>.
    Это наше первое использование библиотеки KIO. {{class|KFileDialog}} предоставляет набор функций для отображения файловых диалогов, которые используют все приложения KDE. Вызов <tt>KFileDialog::getSaveFileName()</tt> отобразит диалог, где пользователь может выбрать файл в который сохранить или создать новый файл для сохранения. Функция возвращает полный путь к файлу, который передается функции <tt>saveFileAs(QString)</tt>.


    ====saveFile()====
    ====saveFile()====
    Line 311: Line 311:
    </code>
    </code>


    There's nothing exciting or new in this function, just the logic to decide whether or not to show the save dialog. If <tt>fileName</tt> is not empty, then the file is saved to <tt>fileName</tt>. But if it is, then the dialog is shown to allow the user to select a file name.
    Тут ничего захватывающего или нового в этой функции, просто условие показывать или нет диалог сохранения. Если <tt>fileName</tt> не пустой, тогда файл сохраняется под именем <tt>fileName</tt>. Но если это не так, то отображаем диалог сохранения, чтобы пользователь мог выбрать файл для сохранения.


    ===Loading a file===
    ===Загрузка файла===


    Finally, we get round to being able to load a file from disc. The code for this is all contained in <tt>MainWindow::openFile()</tt>.
    Наконец, мы не можем обойтись без загрузки фала с диска. Код для этого содержится в <tt>MainWindow::openFile()</tt>.


    First we must ask the user for the name of the file they wish to open. We do this using another one of the <tt>KFileDialog</tt> functions, this time <tt>getOpenFileName()</tt>:
    Сначала мы должны спросить пользователя, какой файл он хочет открыть. Это делается с помощью <tt>KFileDialog</tt>, на этот раз <tt>getOpenFileName()</tt>:
    <code cppqt>
    <code cppqt>
    QString fileNameFromDialog = KFileDialog::getOpenFileName();
    QString fileNameFromDialog = KFileDialog::getOpenFileName();
    </code>
    </code>


    Then we use the KIO library to retrieve our file. This allows us to open the file with QFile even if it's stored in a remote location like an FTP site. We make the following call to {{class|NetAccess}}'s <tt>download()</tt> function
    Затем мы используем библиотеку KIO, чтобы загрузить файл. Это позволяет нам открывать файлы с помощью QFile даже если они расположены удаленно, например FTP. Мы вызываем функцию {{class|NetAccess}} <tt>download()</tt>
    <code cppqt>
    <code cppqt>
    KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)
    KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)
    </code>
    </code>
    The first argument is the name of the file you wish to download. The second is a QString which, after the download is complete, will contain the location of the temporary copy of the file. It is this <tt>tmpFile</tt> we will work with from now on.
    Первый аргумент имя файла, который вы хотите загрузить. Второй -- QString, содержащий путь ко временной копии фала. Именно с <tt>tmpFile</tt> мы будем работать.


    The function returns <tt>true</tt> or <tt>false</tt> depending on whether the transfer was successful. If it failed, we display a message box giving the error:
    Функция возвращает <tt>true</tt> или <tt>false</tt> в зависимости от результата передачи (успешно/ошибка). Если произошла ошибка, мы отображаем сообщение с ошибкой:
    <code cppqt>
    <code cppqt>
    KMessageBox::error(this, KIO::NetAccess::lastErrorString());
    KMessageBox::error(this, KIO::NetAccess::lastErrorString());
    </code>
    </code>


    Otherwise, we continue with opening the file.
    В противном случае, мы продолжаем открывать файл.


    We create a QFile by passing the temporary file created by <tt>NetAccess::download()</tt> to its constructor and then open it in read-only mode
    Мы создаем QFile работая со временным файлом созданным <tt>NetAccess::download()</tt> и открываем его в режиме только для чтения:
    <code cppqt>
    <code cppqt>
    QFile file(tmpFile);
    QFile file(tmpFile);
    Line 341: Line 341:
    </code>
    </code>


    In order to display the contents of the file, we must use a {{qt|QTextStream}}. We create one by passing the contents of our file to its constructor and then call QFile's <tt>readAll()</tt> function to get the text from the file. This is then passed to the <tt>setPlainText()</tt> function of our text area.
    Для отображения содержимого файла, мы используем {{qt|QTextStream}}. Мы создаем QTextStream и передаем в его конструктор содержимое фала, вызываем функцию QFile <tt>readAll()</tt>, что бы прочитать текст из файла. И вот это передается в функцию <tt>setPlainText()</tt> нашей текстовой области.


    <code cppqt>
    <code cppqt>
    Line 347: Line 347:
    </code>
    </code>


    We then store the path of the file we just opened:
    Затем мы сохраняем путь к только что открытому файлу:
    <code cppqt>
    <code cppqt>
    fileName = fileNameFromDialog;
    fileName = fileNameFromDialog;
    </code>
    </code>
    and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:
    и наконец, удаляем временный файл созданный <tt>NetAccess::download()</tt>:
    <code cppqt>
    <code cppqt>
    KIO::NetAccess::removeTempFile(tmpFile);
    KIO::NetAccess::removeTempFile(tmpFile);
    </code>
    </code>


    ==Make, Install And Run==
    ==Сборка, Установка и Запуск==


    ===CMakeLists.txt===
    ===CMakeLists.txt===
    Line 379: Line 379:
             DESTINATION ${DATA_INSTALL_DIR}/tutorial4)
             DESTINATION ${DATA_INSTALL_DIR}/tutorial4)
    </code>
    </code>
    Since we are now using the KIO library, we must tell CMake to link against it. We do this by passing <tt>${KDE4_KIO_LIBS}</tt> to the <tt>target_link_libraries()</tt> function.
    Теперь мы используем библиотеку KIO, мы должны сказать CMake слинковать приложение с ней. Это делается путем передачи <tt>${KDE4_KIO_LIBS}</tt> функции <tt>target_link_libraries()</tt>.


    With this file, the tutorial can be built and run in the same way as tutorial 3. For more information, see tutorial 3.
    С помощью этого файла, урок может быть собран и запущен тем же путем, что и урок 3. Подробнее см. урок 3.
    <code>
    <code>
    mkdir build && cd build
    mkdir build && cd build
    Line 389: Line 389:
    </code>
    </code>


    {{note|Changed settings are saved in your KDE directory, in this case into $HOME/.kde/share/apps/tutorial4.}}
    {{note|Измененные настройки сохраняются в вашем каталог KDE, в этом случае в $HOME/.kde/share/apps/tutorial4.}}


    ==Moving On==
    ==Moving On==
    Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.
    Теперь вы можете переходить к уроку [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]].


    [[Category:C++]]
    [[Category:C++]]

    Revision as of 16:38, 30 May 2011


    Development/Tutorials/Saving_and_loading


    Загрузка и сохранение файлов
    Tutorial Series   Beginner Tutorial
    Previous   Урок 3 - KActions
    What's Next   Tutorial 5 - Using KCmdLineArgs
    Further Reading   Tutorial: Using KIO Slaves in your Program KIO::NetAccess QFile

    Введение

    Мы сделали интерфейс простого текстового редактора, самое время добавить к нему чего-нибудь полезного. Самое основное в чем нуждается текстовый редактор - это загрузка файлов с диска, сохранение файлов, которые были созданы/изменены и создание новых файлов.

    KDE предоставляет набор классов для работы с файлами, которые делают жизнь разработчика намного легче. Библиотека KIO предоставляет вам легкий доступ к файлам через сеть, а так же стандартные диалоги выбора файла.

    Листинг кода

    main.cpp

    1. include <KApplication>
    2. include <KAboutData>
    3. include <KCmdLineArgs>
    1. include "mainwindow.h"

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

     KAboutData aboutData( "tutorial4", "tutorial4",
         ki18n("Tutorial 4"), "1.0",
         ki18n("A simple text area which can load and save."),
         KAboutData::License_GPL,
         ki18n("Copyright (c) 2007 Developer") );
     KCmdLineArgs::init( argc, argv, &aboutData );
     KApplication app;
    
     MainWindow* window = new MainWindow();
     window->show();
     return app.exec();
    

    } main.cpp не изменился с урока 3, изменилась только принадлежность приложения к уроку 4.

    mainwindow.h

    1. ifndef MAINWINDOW_H
    2. define MAINWINDOW_H
    1. include <KXmlGuiWindow>
    2. include <KTextEdit>

    class MainWindow : public KXmlGuiWindow {

     Q_OBJECT //новое
     
     public:
       MainWindow(QWidget *parent=0);
     
     private:
       KTextEdit* textArea;
       void setupActions();
       QString fileName; //новое
    
     private slots: //новое
       void newFile(); //новое
       void openFile(); //новое
       void saveFile(); //новое
       void saveFileAs(); //новое
       void saveFileAs(const QString &outputFileName); //новое
    

    };

    1. endif

    Если мы хотим добавить возможность загружать и сохранять файлы, мы должны добавить функции которые будут делать это. Т.к. функции будут вызваны через механизм Qt сигнал/слот мы должны обозначить, что эти функции - слоты, что мы и делаем на строке 19. Раз мы используем слоты, мы должны добавить макрос Q_OBJECT.

    Так же нам нужно хранить имя открытого файла, поэтому объявляем переменную QString fileName.

    mainwindow.cpp

    1. include "mainwindow.h"
    1. include <KApplication>
    2. include <KAction>
    3. include <KLocale>
    4. include <KActionCollection>
    5. include <KStandardAction>
    6. include <KFileDialog> //новое
    7. include <KMessageBox> //новое
    8. include <KIO/NetAccess> //новое
    9. include <KSaveFile> //новое
    10. include <QTextStream> //новое

    MainWindow::MainWindow(QWidget *parent)

       : KXmlGuiWindow(parent),
         fileName(QString()) //новое
    

    {

     textArea = new KTextEdit;
     setCentralWidget(textArea);
    
     setupActions();
    

    }

    void MainWindow::setupActions() {

     KAction* clearAction = new KAction(this);
     clearAction->setText(i18n("Clear"));
     clearAction->setIcon(KIcon("document-new"));
     clearAction->setShortcut(Qt::CTRL + Qt::Key_W);
     actionCollection()->addAction("clear", clearAction);
     connect(clearAction, SIGNAL(triggered(bool)),
             textArea, SLOT(clear()));
    
     KStandardAction::quit(kapp, SLOT(quit()),
                           actionCollection());
    
     KStandardAction::open(this, SLOT(openFile()),
                           actionCollection()); //новое
    
     KStandardAction::save(this, SLOT(saveFile()),
                           actionCollection()); //новое
    
     KStandardAction::saveAs(this, SLOT(saveFileAs()),
                           actionCollection()); //новое
    
     KStandardAction::openNew(this, SLOT(newFile()),
                           actionCollection()); //новое
    
     setupGUI();
    

    }

    //Дальше все новое

    void MainWindow::newFile() {

     fileName.clear();
     textArea->clear();
    

    }

    void MainWindow::saveFileAs(const QString &outputFileName) {

     KSaveFile file(outputFileName);
     file.open();
     
     QByteArray outputByteArray;
     outputByteArray.append(textArea->toPlainText().toUtf8());
     file.write(outputByteArray);
     file.finalize();
     file.close();
     
     fileName = outputFileName;
    

    }

    void MainWindow::saveFileAs() {

     saveFileAs(KFileDialog::getSaveFileName());
    

    }

    void MainWindow::saveFile() {

     if(!fileName.isEmpty())
     {
       saveFileAs(fileName);
     }
     else
     {
       saveFileAs();
     }
    

    }

    void MainWindow::openFile() {

     QString fileNameFromDialog = KFileDialog::getOpenFileName();
    
     QString tmpFile;
     if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, 
            this))
     {
       QFile file(tmpFile);
       file.open(QIODevice::ReadOnly);
       textArea->setPlainText(QTextStream(&file).readAll());
       fileName = fileNameFromDialog;
    
       KIO::NetAccess::removeTempFile(tmpFile);
     }
     else
     {
       KMessageBox::error(this, 
           KIO::NetAccess::lastErrorString());
     }
    

    }

    tutorial4ui.rc

    <?xml version="1.0" encoding="UTF-8"?> <gui name="tutorial4"

        version="1"
        xmlns="http://www.kde.org/standards/kxmlgui/1.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.kde.org/standards/kxmlgui/1.0
                            http://www.kde.org/standards/kxmlgui/1.0/kxmlgui.xsd" >
    
     <MenuBar>
       <Menu name="file" >
         <Action name="clear" />
       </Menu>
     </MenuBar>
    
     <ToolBar name="mainToolBar" >
       <text>Main Toolbar</text>
       <Action name="clear" />
     </ToolBar>
    

    </gui> Этот файл идентичен tutorial3ui.rc из урока 3, только поле name изменилось на 'tutorial4'. Нам не нужно добавлять никакую информацию о любом KStandardAction т.к. их обработкой занимается KDE автоматически.

    Объяснение

    Хорошо, теперь напишем код, который будет загружать и сохранять. Все это мы допишем в mainwindow.cpp

    Первая штука, которую добавим fileName(QString()) в конструктор MainWindow на строке 16. Это очищает fileName с самого начала.

    Добавление действий

    Первое, что мы собираемся сделать, это предоставить пользователю интерфейс, что бы он мог сказать приложению "загрузить" и "сохранить". Как действие quit в уроке 3, мы будем использовать KStandardActions. На строках с 37 по 47 мы добавляем действия тем же путем, что и действие quit. Каждое из них мы соединяем с соответствующим слотом, который мы объявили в заголовочном файле.

    Создание нового документа

    Первая функция, которую мы создали - newFile(). void MainWindow::newFile() {

     fileName.clear();
     textArea->clear();
    

    } fileName.clear() очищает переменную fileName типа QString, что отражает тот факт, что этого документа еще нет на диске. textArea->clear() очищает область текста, используя функцию, которую мы подключили к clear KAction в уроке 3.

    Сохранение файла

    saveFileAs(QString)

    Теперь разберем наш первый обработчик. Мы собираемся реализовать функцию, которая сохраняет содержимое текстовой области в файл имя которого передается в функцию. KDE предоставляет класс для безопасного сохранения файла именуемый KSaveFile, который является производным от Qt'шного QFile.

    Прототип функции: void MainWindow::saveFileAs(const QString &outputFileName)

    Мы создаем объект KSaveFile и открываем файл: KSaveFile file(outputFileName); file.open();

    Теперь у нас есть файл для записи, нам нужно отформатировать текст в текстовой области в формат, который может быть записан в файл. Для этого, мы создаем QByteArray и заполняем его обычным текстом из текстовой области: QByteArray outputByteArray; outputByteArray.append(textArea->toPlainText().toUtf8()); Теперь у нас есть QByteArray, запишем его в файл с помощью KSaveFile::write(). Если бы мы использовали QFile, он бы моментально сделал бы изменения в тексте. Однако, если возникнет проблемма посреди записи, файл будет поврежден. По этой причине KSaveFile сначала записывает временный файл, а потом, когда вы вызываете KSaveFile::finalize() изменения попадают в текущий файл. file.write(outputByteArray); file.finalize(); file.close(); Наконец, мы записываем в переменную MainWindow fileName имя файла в который только, что сохранили. fileName = outputFileName;

    saveFileAs()

    Эта функция к которой подключек слот saveAs. Она просто вызывает saveFileAs(QString) и передает ей имя файла возвращенное KFileDialog::getSaveFileName().

    void MainWindow::saveFileAs() {

     saveFileAs(KFileDialog::getSaveFileName());
    

    }

    Это наше первое использование библиотеки KIO. KFileDialog предоставляет набор функций для отображения файловых диалогов, которые используют все приложения KDE. Вызов KFileDialog::getSaveFileName() отобразит диалог, где пользователь может выбрать файл в который сохранить или создать новый файл для сохранения. Функция возвращает полный путь к файлу, который передается функции saveFileAs(QString).

    saveFile()

    void MainWindow::saveFile() {

     if(!fileName.isEmpty())
     {
       saveFileAs(fileName);
     }
     else
     {
       saveFileAs();
     }
    

    }

    Тут ничего захватывающего или нового в этой функции, просто условие показывать или нет диалог сохранения. Если fileName не пустой, тогда файл сохраняется под именем fileName. Но если это не так, то отображаем диалог сохранения, чтобы пользователь мог выбрать файл для сохранения.

    Загрузка файла

    Наконец, мы не можем обойтись без загрузки фала с диска. Код для этого содержится в MainWindow::openFile().

    Сначала мы должны спросить пользователя, какой файл он хочет открыть. Это делается с помощью KFileDialog, на этот раз getOpenFileName(): QString fileNameFromDialog = KFileDialog::getOpenFileName();

    Затем мы используем библиотеку KIO, чтобы загрузить файл. Это позволяет нам открывать файлы с помощью QFile даже если они расположены удаленно, например FTP. Мы вызываем функцию NetAccess download() KIO::NetAccess::download(fileNameFromDialog, tmpFile, this) Первый аргумент имя файла, который вы хотите загрузить. Второй -- QString, содержащий путь ко временной копии фала. Именно с tmpFile мы будем работать.

    Функция возвращает true или false в зависимости от результата передачи (успешно/ошибка). Если произошла ошибка, мы отображаем сообщение с ошибкой: KMessageBox::error(this, KIO::NetAccess::lastErrorString());

    В противном случае, мы продолжаем открывать файл.

    Мы создаем QFile работая со временным файлом созданным NetAccess::download() и открываем его в режиме только для чтения: QFile file(tmpFile); file.open(QIODevice::ReadOnly);

    Для отображения содержимого файла, мы используем QTextStream. Мы создаем QTextStream и передаем в его конструктор содержимое фала, вызываем функцию QFile readAll(), что бы прочитать текст из файла. И вот это передается в функцию setPlainText() нашей текстовой области.

    textArea->setPlainText(QTextStream(&file).readAll());

    Затем мы сохраняем путь к только что открытому файлу: fileName = fileNameFromDialog; и наконец, удаляем временный файл созданный NetAccess::download(): KIO::NetAccess::removeTempFile(tmpFile);

    Сборка, Установка и Запуск

    CMakeLists.txt

    project(tutorial4)

    find_package(KDE4 REQUIRED) include_directories(${KDE4_INCLUDES})

    set(tutorial4_SRCS

     main.cpp
     mainwindow.cpp
    

    )

    kde4_add_executable(tutorial4 ${tutorial4_SRCS})

    target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS}

                                   ${KDE4_KIO_LIBS})
    
    

    install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR}) install(FILES tutorial4ui.rc

           DESTINATION ${DATA_INSTALL_DIR}/tutorial4)
    

    Теперь мы используем библиотеку KIO, мы должны сказать CMake слинковать приложение с ней. Это делается путем передачи ${KDE4_KIO_LIBS} функции target_link_libraries().

    С помощью этого файла, урок может быть собран и запущен тем же путем, что и урок 3. Подробнее см. урок 3. mkdir build && cd build cmake .. -DCMAKE_INSTALL_PREFIX=$HOME make install $HOME/bin/tutorial4

    Note
    Измененные настройки сохраняются в вашем каталог KDE, в этом случае в $HOME/.kde/share/apps/tutorial4.


    Moving On

    Теперь вы можете переходить к уроку KCmdLineArgs.