Archive:Development/Tutorials/Saving and loading (zh TW): Difference between revisions
No edit summary |
No edit summary |
||
Line 11: | Line 11: | ||
next=[[Development/Tutorials/KCmdLineArgs|教學 5 - 使用 KCmdLineArgs]]| | next=[[Development/Tutorials/KCmdLineArgs|教學 5 - 使用 KCmdLineArgs]]| | ||
reading=[[Development/Tutorials/KIO Slaves/Using KIO Slaves in your Program|教學: | reading=[[Development/Tutorials/KIO Slaves/Using KIO Slaves in your Program|教學: 在你的程式使用 KIO Slaves]]、KIO::{{class|NetAccess}}、{{qt|QFile}} | ||
}} | }} | ||
Line 221: | Line 221: | ||
</gui> | </gui> | ||
</code> | </code> | ||
這和教學 3 的 <tt>tutorial3ui.rc</tt> 相同,除了 <tt>name</tt> 改為 'tutorial4' 以外。我們不需要加入任何 <tt>KStandardAction</tt> 的資訊來安置這些動作,KDE 會自動處理。 | |||
==解釋== | ==解釋== | ||
Okay,現在實現的程式碼將執行載入和儲存。這都實做在 <tt>mainwindow.cpp</tt> | |||
首先我們加入 | |||
<code cppqt> | <code cppqt> | ||
fileName(QString()) | fileName(QString()) | ||
</code> | </code> | ||
在 <tt>MainWindow</tt> 建構子列表的第16行。這可以確保 <tt>fileName</tt>一開始是空的。 | |||
===加入動作=== | ===加入動作=== | ||
我們首先要做的是為使用者提供操作介面,使他們能夠告訴應用程式載入和儲存。類似教學 3的 <tt>quit</tt> 動作,我們將使用 <tt>KStandardActions</tt>。在37至47行,我們用和 <tt>quit</tt> 動作同樣的方式加入動作。我們將每一項連接到適當的槽,並宣告在標頭檔中。 | |||
===創建新文件=== | |||
我們第一個創建的函數是 <tt>newFile()</tt> 。 | |||
<code cppqt> | <code cppqt> | ||
void MainWindow::newFile() | void MainWindow::newFile() | ||
Line 247: | Line 250: | ||
} | } | ||
</code> | </code> | ||
<tt>fileName.clear()</tt> | |||
<tt>fileName.clear()</tt> 會設定 <tt>fileName</tt> QString 是空的,以反映該文件還沒有存在於硬碟的事實。<tt>textArea->clear()</tt> 會清除中央的文字區,使用在教學 3我們連接 <tt>clear</tt> <tt>KAction</tt> 的相同功能函式。 | |||
===儲存檔案=== | ===儲存檔案=== |
Revision as of 10:30, 29 September 2009
Development/Tutorials/Saving_and_loading
Languages: عربي | Asturianu | Català | Česky | Kaszëbsczi | Dansk | Deutsch | English | Esperanto | Español | Eesti | فارسی | Suomi | Français | Galego | Italiano | 日本語 | 한국어 | Norwegian | Polski | Português Brasileiro | Română | Русский | Svenska | Slovenčina | Slovenščina | српски | Türkçe | Tiếng Việt | Українська | 简体中文 | 繁體中文
Template:TutorialBrowser (zh TW)
摘要
現在我們擁有了一個基本的文字編輯器界面,開始要讓他做一些有用的事情了。最根本的來說,一個文字編輯器需要能夠從硬碟中載入檔案,儲存你新增或編輯過的檔案。
KDE 提供了許多讓開發者能輕鬆操作檔案的類別。KIO 函式庫讓你可以十分容易地透過網路協定訪問檔案,而且提供標準的檔案對話框。
程式碼
main.cpp
- include <KApplication>
- include <KAboutData>
- include <KCmdLineArgs>
- 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中的相比沒什麼變化,除了說明參數從 tutorial 3 變為了 tutorial 4。
mainwindow.h
- ifndef MAINWINDOW_H
- define MAINWINDOW_H
- include <KXmlGuiWindow>
- include <KTextEdit>
class MainWindow : public KXmlGuiWindow
{
Q_OBJECT //與教學 3相比,新增加的
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); //新增的
};
- endif
由於我們想要加上載入和儲存檔案的能力,所以我們必須加入用來完成這些工作的函數。由於這些函數將會透過Qt的訊號/槽(signal/slot) 機制被呼叫,所以我們必須註明這些函數是槽(slots),就像我們在第19行做的那樣。由於我們在標頭檔中使用槽,所以我們同樣必須加入Q_OBJECT 巨集。
我們同樣想要跟踪當前打開檔案的名稱,所以我們宣告了一個QString fileName 。
mainwindow.cpp
- include "mainwindow.h"
- include <KApplication>
- include <KAction>
- include <KLocale>
- include <KActionCollection>
- include <KStandardAction>
- include <KFileDialog> //新增的
- include <KMessageBox> //新增的
- include <KIO/NetAccess> //新增的
- include <KSaveFile> //新增的
- 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>
這和教學 3 的 tutorial3ui.rc 相同,除了 name 改為 'tutorial4' 以外。我們不需要加入任何 KStandardAction 的資訊來安置這些動作,KDE 會自動處理。
解釋
Okay,現在實現的程式碼將執行載入和儲存。這都實做在 mainwindow.cpp
首先我們加入
fileName(QString())
在 MainWindow 建構子列表的第16行。這可以確保 fileName一開始是空的。
加入動作
我們首先要做的是為使用者提供操作介面,使他們能夠告訴應用程式載入和儲存。類似教學 3的 quit 動作,我們將使用 KStandardActions。在37至47行,我們用和 quit 動作同樣的方式加入動作。我們將每一項連接到適當的槽,並宣告在標頭檔中。
創建新文件
我們第一個創建的函數是 newFile() 。
void MainWindow::newFile()
{
fileName.clear();
textArea->clear();
}
fileName.clear() 會設定 fileName QString 是空的,以反映該文件還沒有存在於硬碟的事實。textArea->clear() 會清除中央的文字區,使用在教學 3我們連接 clear KAction 的相同功能函式。
儲存檔案
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 KSaveFile which is derived from Qt's QFile.
The function's prototype is
void MainWindow::saveFileAs(const QString &outputFileName)
We then create our KSaveFile object and open it with
KSaveFile file(outputFileName);
file.open();
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 QByteArray and fill it with the plain text version of whatever is in the text area:
QByteArray outputByteArray;
outputByteArray.append(textArea->toPlainText().toUtf8());
Now that we have our QByteArray, we use it to write to the file with KSaveFile::write(). If we were using a normal QFile, this would make the changes immediately. However, if a problem occurred partway through writing, the file would become corrupted. For this reason, KSaveFile works by first writing to a temporary file and then, when you call KSaveFile::finalize() the changes are made to the actual file.
file.write(outputByteArray);
file.finalize();
file.close();
Finally, we set MainWindows's fileName member to point to the file name we just saved to.
fileName = outputFileName;
saveFileAs()
This is the function that the saveAs slot is connected to. It simply calls the generic saveFileAs(QString) function and passes the file name returned by KFileDialog::getSaveFileName().
void MainWindow::saveFileAs()
{
saveFileAs(KFileDialog::getSaveFileName());
}
This is our first actual use of the KIO library. KFileDialog provides a number of static functions for displaying the common file dialog that is used by all KDE applications. Calling KFileDialog::getSaveFileName() 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 saveFileAs(QString).
saveFile()
void MainWindow::saveFile()
{
if(!fileName.isEmpty())
{
saveFileAs(fileName);
}
else
{
saveFileAs();
}
}
There's nothing exciting or new in this function, just the logic to decide whether or not to show the save dialog. If fileName is not empty, then the file is saved to fileName. But if it is, then the dialog is shown to allow the user to select a file name.
載入檔案
Finally, we get round to being able to load a file from disc. The code for this is all contained in MainWindow::openFile().
First we must ask the user for the name of the file they wish to open. We do this using another one of the KFileDialog functions, this time getOpenFileName():
QString fileNameFromDialog = KFileDialog::getOpenFileName();
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 NetAccess's download() function
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)
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 tmpFile we will work with from now on.
The function returns true or false depending on whether the transfer was successful. If it failed, we display a message box giving the error:
KMessageBox::error(this, KIO::NetAccess::lastErrorString());
Otherwise, we continue with opening the file.
We create a QFile by passing the temporary file created by NetAccess::download() to its constructor and then open it in read-only mode
QFile file(tmpFile);
file.open(QIODevice::ReadOnly);
In order to display the contents of the file, we must use a QTextStream. We create one by passing the contents of our file to its constructor and then call QFile's readAll() function to get the text from the file. This is then passed to the setPlainText() function of our text area.
textArea->setPlainText(QTextStream(&file).readAll());
We then store the path of the file we just opened:
fileName = fileNameFromDialog;
and finally, we remove the temporary file that was created by 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)
Since we are now using the KIO library, we must tell CMake to link against it. We do this by passing ${KDE4_KIO_LIBS} to the target_link_libraries() function.
With this file, the tutorial can be built and run in the same way as tutorial 3. For more information, see tutorial 3.
mkdir build && cd build
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME
make install
$HOME/bin/tutorial4
繼續前進
現在你可以開始學習下一課:KCmdLineArgs 教學。