Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Home
Help
Recent changes
Contributor Help Pages
Tasks and Tools
Modify a page
Add new content
Page elements
Typographical guidelines
More markup help
Translator Help Pages
Get a Translator Account
Languages represented
Translation Workflow
Translate a Page
Off-line Translation
Translation Statistics
More Help pages
Search
Search
English
Log in
Personal tools
Log in
Export translations
Translate
English
Language statistics
Message group statistics
Export
Tools
Tools
move to sidebar
hide
Actions
Language statistics
Message group statistics
Export
General
Special pages
Printable version
Settings
Group
Category:Phonon
Contribute/List of KDE Modules
Development
Development/FAQs/General FAQ
Development/FAQs/Technical FAQ
Development/KDevelop-PG-Qt Introduction
Development/Tools
Development/Tutorials
Development/Tutorials/CommandLineArguments
Development/Tutorials/Common Programming Mistakes
Development/Tutorials/First program
Development/Tutorials/First program/KDE4
Development/Tutorials/First program/KF5
Development/Tutorials/KDE3/Qt Designer and KDevelop 3.0 for Beginners
Development/Tutorials/Metadata/Nepomuk/TipsAndTricks
Development/Tutorials/Physical Simulation
Development/Tutorials/Qt4 Ruby Tutorial
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 01
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 04
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 05
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 06
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 07
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 08
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 09
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 10
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 12
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 13
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 14
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 2
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 3
Development/Tutorials/Saving and loading
Development/Tutorials/Setting Up
Development/Tutorials/Using Actions
Development/Tutorials/Using KXmlGuiWindow
Documentation Primer
Edit Markup
Getting Started
Help:Contents
Help:Contribute
How To Convert a UserBase Manual to Docbook
KDE Frameworks
KDE Frameworks/Getting Started
KDE TechBase:About
KDE TechBase:Contributors
KDE TechBase:General disclaimer
KDE TechBase:Privacy policy
Off-line Translation
Projects/Calligra/Plugin Tutorials
Toolbox
Translate a Page
Translation Workflow
Typographical Guidelines
User:Neverendingo
Welcome to KDE TechBase
Language
aa - Afar
ab - Abkhazian
abs - Ambonese Malay
ace - Achinese
acm - Iraqi Arabic
ady - Adyghe
ady-cyrl - Adyghe (Cyrillic script)
aeb - Tunisian Arabic
aeb-arab - Tunisian Arabic (Arabic script)
aeb-latn - Tunisian Arabic (Latin script)
af - Afrikaans
aln - Gheg Albanian
alt - Southern Altai
am - Amharic
ami - Amis
an - Aragonese
ang - Old English
ann - Obolo
anp - Angika
ar - Arabic
arc - Aramaic
arn - Mapuche
arq - Algerian Arabic
ary - Moroccan Arabic
arz - Egyptian Arabic
as - Assamese
ase - American Sign Language
ast - Asturian
atj - Atikamekw
av - Avaric
avk - Kotava
awa - Awadhi
ay - Aymara
az - Azerbaijani
azb - South Azerbaijani
ba - Bashkir
ban - Balinese
ban-bali - Balinese (Balinese script)
bar - Bavarian
bbc - Batak Toba
bbc-latn - Batak Toba (Latin script)
bcc - Southern Balochi
bci - Baoulé
bcl - Central Bikol
bdr - West Coast Bajau
be - Belarusian
be-tarask - Belarusian (Taraškievica orthography)
bew - Betawi
bg - Bulgarian
bgn - Western Balochi
bh - Bhojpuri
bho - Bhojpuri
bi - Bislama
bjn - Banjar
blk - Pa'O
bm - Bambara
bn - Bangla
bo - Tibetan
bpy - Bishnupriya
bqi - Bakhtiari
br - Breton
brh - Brahui
bs - Bosnian
btm - Batak Mandailing
bto - Iriga Bicolano
bug - Buginese
bxr - Russia Buriat
ca - Catalan
cbk-zam - Chavacano
cdo - Min Dong Chinese
ce - Chechen
ceb - Cebuano
ch - Chamorro
cho - Choctaw
chr - Cherokee
chy - Cheyenne
ckb - Central Kurdish
co - Corsican
cps - Capiznon
cpx - Pu-Xian Min
cpx-hans - Pu-Xian Min (Simplified Han script)
cpx-hant - Pu-Xian Min (Traditional Han script)
cpx-latn - Pu-Xian Min (Latin script)
cr - Cree
crh - Crimean Tatar
crh-cyrl - Crimean Tatar (Cyrillic script)
crh-latn - Crimean Tatar (Latin script)
crh-ro - Crimean Tatar (Romania)
cs - Czech
csb - Kashubian
cu - Church Slavic
cv - Chuvash
cy - Welsh
da - Danish
dag - Dagbani
de - German
de-at - Austrian German
de-ch - Swiss High German
de-formal - German (formal address)
dga - Dagaare
din - Dinka
diq - Zazaki
dsb - Lower Sorbian
dtp - Central Dusun
dty - Doteli
dv - Divehi
dz - Dzongkha
ee - Ewe
egl - Emilian
el - Greek
eml - Emiliano-Romagnolo
en - English
en-ca - Canadian English
en-gb - British English
eo - Esperanto
es - Spanish
es-419 - Latin American Spanish
es-formal - Spanish (formal address)
et - Estonian
eu - Basque
ext - Extremaduran
fa - Persian
fat - Fanti
ff - Fula
fi - Finnish
fit - Tornedalen Finnish
fj - Fijian
fo - Faroese
fon - Fon
fr - French
frc - Cajun French
frp - Arpitan
frr - Northern Frisian
fur - Friulian
fy - Western Frisian
ga - Irish
gaa - Ga
gag - Gagauz
gan - Gan Chinese
gan-hans - Gan (Simplified)
gan-hant - Gan (Traditional)
gcr - Guianan Creole
gd - Scottish Gaelic
gl - Galician
gld - Nanai
glk - Gilaki
gn - Guarani
gom - Goan Konkani
gom-deva - Goan Konkani (Devanagari script)
gom-latn - Goan Konkani (Latin script)
gor - Gorontalo
got - Gothic
gpe - Ghanaian Pidgin
grc - Ancient Greek
gsw - Alemannic
gu - Gujarati
guc - Wayuu
gur - Frafra
guw - Gun
gv - Manx
ha - Hausa
hak - Hakka Chinese
haw - Hawaiian
he - Hebrew
hi - Hindi
hif - Fiji Hindi
hif-latn - Fiji Hindi (Latin script)
hil - Hiligaynon
hno - Northern Hindko
ho - Hiri Motu
hr - Croatian
hrx - Hunsrik
hsb - Upper Sorbian
hsn - Xiang Chinese
ht - Haitian Creole
hu - Hungarian
hu-formal - Hungarian (formal address)
hy - Armenian
hyw - Western Armenian
hz - Herero
ia - Interlingua
id - Indonesian
ie - Interlingue
ig - Igbo
igl - Igala
ii - Sichuan Yi
ik - Inupiaq
ike-cans - Eastern Canadian (Aboriginal syllabics)
ike-latn - Eastern Canadian (Latin script)
ilo - Iloko
inh - Ingush
io - Ido
is - Icelandic
it - Italian
iu - Inuktitut
ja - Japanese
jam - Jamaican Creole English
jbo - Lojban
jut - Jutish
jv - Javanese
ka - Georgian
kaa - Kara-Kalpak
kab - Kabyle
kai - Karekare
kbd - Kabardian
kbd-cyrl - Kabardian (Cyrillic script)
kbp - Kabiye
kcg - Tyap
kea - Kabuverdianu
kg - Kongo
khw - Khowar
ki - Kikuyu
kiu - Kirmanjki
kj - Kuanyama
kjh - Khakas
kjp - Eastern Pwo
kk - Kazakh
kk-arab - Kazakh (Arabic script)
kk-cn - Kazakh (China)
kk-cyrl - Kazakh (Cyrillic script)
kk-kz - Kazakh (Kazakhstan)
kk-latn - Kazakh (Latin script)
kk-tr - Kazakh (Turkey)
kl - Kalaallisut
km - Khmer
kn - Kannada
ko - Korean
ko-kp - Korean (North Korea)
koi - Komi-Permyak
kr - Kanuri
krc - Karachay-Balkar
kri - Krio
krj - Kinaray-a
krl - Karelian
ks - Kashmiri
ks-arab - Kashmiri (Arabic script)
ks-deva - Kashmiri (Devanagari script)
ksh - Colognian
ksw - S'gaw Karen
ku - Kurdish
ku-arab - Kurdish (Arabic script)
ku-latn - Kurdish (Latin script)
kum - Kumyk
kus - Kʋsaal
kv - Komi
kw - Cornish
ky - Kyrgyz
la - Latin
lad - Ladino
lb - Luxembourgish
lbe - Lak
lez - Lezghian
lfn - Lingua Franca Nova
lg - Ganda
li - Limburgish
lij - Ligurian
liv - Livonian
lki - Laki
lld - Ladin
lmo - Lombard
ln - Lingala
lo - Lao
loz - Lozi
lrc - Northern Luri
lt - Lithuanian
ltg - Latgalian
lus - Mizo
luz - Southern Luri
lv - Latvian
lzh - Literary Chinese
lzz - Laz
mad - Madurese
mag - Magahi
mai - Maithili
map-bms - Basa Banyumasan
mdf - Moksha
mg - Malagasy
mh - Marshallese
mhr - Eastern Mari
mi - Māori
min - Minangkabau
mk - Macedonian
ml - Malayalam
mn - Mongolian
mnc - Manchu
mnc-latn - Manchu (Latin script)
mnc-mong - Manchu (Mongolian script)
mni - Manipuri
mnw - Mon
mo - Moldovan
mos - Mossi
mr - Marathi
mrh - Mara
mrj - Western Mari
ms - Malay
ms-arab - Malay (Jawi script)
mt - Maltese
mus - Muscogee
mwl - Mirandese
my - Burmese
myv - Erzya
mzn - Mazanderani
na - Nauru
nah - Nāhuatl
nan - Min Nan Chinese
nap - Neapolitan
nb - Norwegian Bokmål
nds - Low German
nds-nl - Low Saxon
ne - Nepali
new - Newari
ng - Ndonga
nia - Nias
niu - Niuean
nl - Dutch
nl-informal - Dutch (informal address)
nmz - Nawdm
nn - Norwegian Nynorsk
no - Norwegian
nod - Northern Thai
nog - Nogai
nov - Novial
nqo - N’Ko
nrm - Norman
nso - Northern Sotho
nv - Navajo
ny - Nyanja
nyn - Nyankole
nys - Nyungar
oc - Occitan
ojb - Northwestern Ojibwa
olo - Livvi-Karelian
om - Oromo
or - Odia
os - Ossetic
pa - Punjabi
pag - Pangasinan
pam - Pampanga
pap - Papiamento
pcd - Picard
pcm - Nigerian Pidgin
pdc - Pennsylvania German
pdt - Plautdietsch
pfl - Palatine German
pi - Pali
pih - Norfuk / Pitkern
pl - Polish
pms - Piedmontese
pnb - Western Punjabi
pnt - Pontic
prg - Prussian
ps - Pashto
pt - Portuguese
pt-br - Brazilian Portuguese
pwn - Paiwan
qu - Quechua
qug - Chimborazo Highland Quichua
rgn - Romagnol
rif - Riffian
rki - Arakanese
rm - Romansh
rmc - Carpathian Romani
rmy - Vlax Romani
rn - Rundi
ro - Romanian
roa-tara - Tarantino
rsk - Pannonian Rusyn
ru - Russian
rue - Rusyn
rup - Aromanian
ruq - Megleno-Romanian
ruq-cyrl - Megleno-Romanian (Cyrillic script)
ruq-latn - Megleno-Romanian (Latin script)
rw - Kinyarwanda
ryu - Okinawan
sa - Sanskrit
sah - Yakut
sat - Santali
sc - Sardinian
scn - Sicilian
sco - Scots
sd - Sindhi
sdc - Sassarese Sardinian
sdh - Southern Kurdish
se - Northern Sami
se-fi - Northern Sami (Finland)
se-no - Northern Sami (Norway)
se-se - Northern Sami (Sweden)
sei - Seri
ses - Koyraboro Senni
sg - Sango
sgs - Samogitian
sh - Serbo-Croatian
sh-cyrl - Serbo-Croatian (Cyrillic script)
sh-latn - Serbo-Croatian (Latin script)
shi - Tachelhit
shi-latn - Tachelhit (Latin script)
shi-tfng - Tachelhit (Tifinagh script)
shn - Shan
shy - Shawiya
shy-latn - Shawiya (Latin script)
si - Sinhala
simple - Simple English
sjd - Kildin Sami
sje - Pite Sami
sk - Slovak
skr - Saraiki
skr-arab - Saraiki (Arabic script)
sl - Slovenian
sli - Lower Silesian
sm - Samoan
sma - Southern Sami
smn - Inari Sami
sms - Skolt Sami
sn - Shona
so - Somali
sq - Albanian
sr - Serbian
sr-ec - српски (ћирилица)
sr-el - srpski (latinica)
srn - Sranan Tongo
sro - Campidanese Sardinian
ss - Swati
st - Southern Sotho
stq - Saterland Frisian
sty - Siberian Tatar
su - Sundanese
sv - Swedish
sw - Swahili
syl - Sylheti
szl - Silesian
szy - Sakizaya
ta - Tamil
tay - Tayal
tcy - Tulu
tdd - Tai Nuea
te - Telugu
tet - Tetum
tg - Tajik
tg-cyrl - Tajik (Cyrillic script)
tg-latn - Tajik (Latin script)
th - Thai
ti - Tigrinya
tk - Turkmen
tl - Tagalog
tly - Talysh
tly-cyrl - Talysh (Cyrillic script)
tn - Tswana
to - Tongan
tok - Toki Pona
tpi - Tok Pisin
tr - Turkish
tru - Turoyo
trv - Taroko
ts - Tsonga
tt - Tatar
tt-cyrl - Tatar (Cyrillic script)
tt-latn - Tatar (Latin script)
tum - Tumbuka
tw - Twi
ty - Tahitian
tyv - Tuvinian
tzm - Central Atlas Tamazight
udm - Udmurt
ug - Uyghur
ug-arab - Uyghur (Arabic script)
ug-latn - Uyghur (Latin script)
uk - Ukrainian
ur - Urdu
uz - Uzbek
uz-cyrl - Uzbek (Cyrillic script)
uz-latn - Uzbek (Latin script)
ve - Venda
vec - Venetian
vep - Veps
vi - Vietnamese
vls - West Flemish
vmf - Main-Franconian
vmw - Makhuwa
vo - Volapük
vot - Votic
vro - Võro
wa - Walloon
wal - Wolaytta
war - Waray
wls - Wallisian
wo - Wolof
wuu - Wu Chinese
wuu-hans - Wu Chinese (Simplified)
wuu-hant - Wu Chinese (Traditional)
xal - Kalmyk
xh - Xhosa
xmf - Mingrelian
xsy - Saisiyat
yi - Yiddish
yo - Yoruba
yrl - Nheengatu
yue - Cantonese
yue-hans - Cantonese (Simplified)
yue-hant - Cantonese (Traditional)
za - Zhuang
zea - Zeelandic
zgh - Standard Moroccan Tamazight
zh - Chinese
zh-cn - Chinese (China)
zh-hans - Simplified Chinese
zh-hant - Traditional Chinese
zh-hk - Chinese (Hong Kong)
zh-mo - Chinese (Macau)
zh-my - Chinese (Malaysia)
zh-sg - Chinese (Singapore)
zh-tw - Chinese (Taiwan)
zu - Zulu
qqq - Message documentation
Format
Export for off-line translation
Export in native format
Export in CSV format
Fetch
{{DISPLAYTITLE:Développement/Tutoriels/Enregistrer et charger}}<languages/> {{TutorialBrowser| series=Beginner Tutorial| name=Loading and saving files| pre=[[Development/Tutorials/Using_Actions|Tutorial 3 - Actions]]| next=[[Development/Tutorials/CommandLineArguments|Tutorial 5 - Using Command Line Arguments]]| reading=[[Development/Tutorials/KIO Slaves/Using KIO Slaves in your Program|Tutorial: Using KIO Slaves in your Program]] KIO::{{class|NetAccess}} {{qt|QFile}} }} <span id="Abstract"></span> == Présentation == Now that we have a basic text editor interface, it's time to make it do something useful. At the most basic, a text editor needs to be able to load files from data storage, save files that you've created/edited, and create new files. The KDE Frameworks provides a number of classes for working with files that make life a lot easier for developers. The KIO framework allows you to easily access files through network-transparent protocols. At the same time, Qt also provides standard file dialogs for opening and saving files. [[image:tutorial4-kf5.png|frame|center]] <span id="The_Code"></span> == Le code == <span id="main.cpp"></span> === main.cpp === <syntaxhighlight lang="cpp-qt"> #include <cstdlib> #include <QApplication> #include <QCommandLineParser> #include <KAboutData> #include <KLocalizedString> #include "mainwindow.h" int main (int argc, char *argv[]) { QApplication app(argc, argv); KLocalizedString::setApplicationDomain("tutorial4"); KAboutData aboutData( // The program name used internally. (componentName) QStringLiteral("tutorial4"), // A displayable program name string. (displayName) i18n("Tutorial 4"), // The program version string. (version) QStringLiteral("1.0"), // Short description of what the app does. (shortDescription) i18n("A simple text area which can load and save."), // The license this code is released under KAboutLicense::GPL, // Copyright Statement (copyrightStatement = QString()) i18n("(c) 2015"), // Optional text shown in the About box. // Can contain any information desired. (otherText) i18n("Some text..."), // The program homepage string. (homePageAddress = QString()) QStringLiteral("http://example.com/"), // The bug report email address // (bugsEmailAddress = QLatin1String("submit@bugs.kde.org") QStringLiteral("submit@bugs.kde.org")); aboutData.addAuthor(i18n("Name"), i18n("Task"), QStringLiteral("your@email.com"), QStringLiteral("http://your.website.com"), QStringLiteral("OSC Username")); KAboutData::setApplicationData(aboutData); QCommandLineParser parser; aboutData.setupCommandLine(&parser); parser.process(app); aboutData.processCommandLine(&parser); MainWindow* window = new MainWindow(); window->show(); return app.exec(); } </syntaxhighlight> <tt>main.cpp</tt> hasn't changed from tutorial 3 except to change any reference from tutorial 3 to tutorial 4. <span id="mainwindow.h"></span> === mainwindow.h === <syntaxhighlight lang="cpp-qt"> #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <KXmlGuiWindow> class KTextEdit; class KJob; class MainWindow : public KXmlGuiWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); private: void setupActions(); private slots: void newFile(); void openFile(); void saveFile(); void saveFileAs(); void saveFileAs(const QString &outputFileName); void downloadFinished(KJob* job); private: KTextEdit* textArea; QString fileName; }; #endif </syntaxhighlight> Since we want to add the ability to load and save files, we must add the functions which will do the work. Since the functions will be called through Qt's [http://doc.qt.io/qt-5/signalsandslots.html signal/slot] mechanism we must specify that these functions are slots. Since we are using slots in this header file, we must also add the [http://doc.qt.io/qt-5/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] macro. We also want to keep track of the filename of the currently opened file so we declare a <tt>[http://doc.qt.io/qt-5/qstring.html QString] fileName</tt>. <span id="mainwindow.cpp"></span> === mainwindow.cpp === <syntaxhighlight lang="cpp-qt"> #include <QApplication> #include <QAction> #include <QSaveFile> #include <QFileDialog> #include <QTextStream> #include <QByteArray> #include <KTextEdit> #include <KLocalizedString> #include <KActionCollection> #include <KStandardAction> #include <KMessageBox> #include <KIO/Job> #include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : KXmlGuiWindow(parent), fileName(QString()) { textArea = new KTextEdit(); setCentralWidget(textArea); setupActions(); } void MainWindow::setupActions() { QAction* clearAction = new QAction(this); clearAction->setText(i18n("&Clear")); clearAction->setIcon(QIcon::fromTheme("document-new")); actionCollection()->setDefaultShortcut(clearAction, Qt::CTRL + Qt::Key_W); actionCollection()->addAction("clear", clearAction); connect(clearAction, SIGNAL(triggered(bool)), textArea, SLOT(clear())); KStandardAction::quit(qApp, 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(Default, "tutorial4ui.rc"); } void MainWindow::newFile() { fileName.clear(); textArea->clear(); } void MainWindow::saveFileAs(const QString &outputFileName) { if (!outputFileName.isNull()) { QSaveFile file(outputFileName); file.open(QIODevice::WriteOnly); QByteArray outputByteArray; outputByteArray.append(textArea->toPlainText().toUtf8()); file.write(outputByteArray); file.commit(); fileName = outputFileName; } } void MainWindow::saveFileAs() { saveFileAs(QFileDialog::getSaveFileName(this, i18n("Save File As"))); } void MainWindow::saveFile() { if (!fileName.isEmpty()) { saveFileAs(fileName); } else { saveFileAs(); } } void MainWindow::openFile() { QUrl fileNameFromDialog = QFileDialog::getOpenFileUrl(this, i18n("Open File")); if (!fileNameFromDialog.isEmpty()) { KIO::Job* job = KIO::storedGet(fileNameFromDialog); fileName = fileNameFromDialog.toLocalFile(); connect(job, SIGNAL(result(KJob*)), this, SLOT(downloadFinished(KJob*))); job->exec(); } } void MainWindow::downloadFinished(KJob* job) { if (job->error()) { KMessageBox::error(this, job->errorString()); fileName.clear(); return; } KIO::StoredTransferJob* storedJob = (KIO::StoredTransferJob*)job; textArea->setPlainText(QTextStream(storedJob->data(), QIODevice::ReadOnly).readAll()); } </syntaxhighlight> We'll get into the details of <tt>mainwindow.cpp</tt> in a while. <span id="tutorial4ui.rc"></span> === tutorial4ui.rc === <syntaxhighlight lang="xml"> <?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> </syntaxhighlight> This is identical to <tt>tutorial3ui.rc</tt> from tutorial 3 except the <tt>name</tt> has changed to 'tutorial4'. We do not need to add any information about any of the <tt>KStandardAction</tt>s since the placement of those actions is handled automatically by KDE. <span id="Explanation"></span> == Explications == Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt> The first thing we do is add <tt>fileName(QString())</tt> to the <tt>MainWindow</tt> constructor list to make sure that <tt>fileName</tt> is empty right from the beginning. <span id="Adding_the_actions"></span> === Ajouter les actions === 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>. We add the actions in the same way as for the <tt>quit</tt> action and, for each one, we connect it to the appropriate slot that we declared in the header file. <span id="Creating_a_new_document"></span> === Créer un nouveau document === The first function we create is the <tt>newFile()</tt> function. <syntaxhighlight lang="cpp-qt"> void MainWindow::newFile() { fileName.clear(); textArea->clear(); } </syntaxhighlight> <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 storage. <tt>textArea->clear()</tt> then clears the central text area using the same function that we connected the <tt>clear</tt> <tt>KQction</tt> to in tutorial 3. {{Warning|This simple example simply clears the text area without checking if the file has been saved first. It's only meant as a demonstration of file I/O and not as an example of best programming practices.}} <span id="Saving_a_file"></span> === Enregistrer un fichier === {{Note|To make this tutorial simple, this example program can only save to local storage even though it can open any file from any location, even those from remote sources.}} <span id="saveFileAs(QString)"></span> ==== 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. Qt provides a class for safely saving a file called [http://doc.qt.io/qt-5/qsavefile.html QSaveFile]. The function's prototype is <syntaxhighlight lang="cpp-qt"> void MainWindow::saveFileAs(const QString &outputFileName) </syntaxhighlight> We then create our <tt>QSaveFile</tt> object and open it with <syntaxhighlight lang="cpp-qt"> QSaveFile file(outputFileName); file.open(QIODevice::WriteOnly); </syntaxhighlight> 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 [http://doc.qt.io/qt-5/qbytearray.html QByteArray] and fill it with the plain text version of whatever is in the text area: <syntaxhighlight lang="cpp-qt"> QByteArray outputByteArray; outputByteArray.append(textArea->toPlainText().toUtf8()); </syntaxhighlight> Now that we have our <tt>QByteArray</tt>, we use it to write to the file with <tt>QSaveFile::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>QSaveFile</tt> works by first writing to a temporary file and then, when you call <tt>QSaveFile::commit()</tt> the changes are made to the actual file. <tt>commit()</tt> also closes the file. <syntaxhighlight lang="cpp-qt"> file.write(outputByteArray); file.commit(); </syntaxhighlight> Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to. <syntaxhighlight lang="cpp-qt"> fileName = outputFileName; </syntaxhighlight> <span id="saveFileAs()"></span> ==== 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>[http://doc.qt.io/qt-5/qfiledialog.html QFileDialog]::[http://doc.qt.io/qt-5/qfiledialog.html#getSaveFileName getSaveFileName()]</tt>. <syntaxhighlight lang="cpp-qt"> void MainWindow::saveFileAs() { saveFileAs(QFileDialog::getSaveFileName(this, i18n("Save File As"))); } </syntaxhighlight> [http://doc.qt.io/qt-5/qfiledialog.html QFileDialog] provides a number of static functions for displaying the common file dialog that is used by all KDE applications. Calling <tt>QFileDialog::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>. <span id="saveFile()"></span> ==== saveFile() ==== <syntaxhighlight lang="cpp-qt"> void MainWindow::saveFile() { if(!fileName.isEmpty()) { saveFileAs(fileName); } else { saveFileAs(); } } </syntaxhighlight> 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. <span id="Loading_a_file"></span> === Charger un fichier === Finally, we get round to being able to load a file, from local storage or from a remote location like an FTP server. The code for this is all contained in <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>QFileDialog</tt> functions, this time <tt>getOpenFileName()</tt>: <syntaxhighlight lang="cpp-qt"> QUrl fileNameFromDialog = QFileDialog::getOpenFileUrl(this, i18n("Open File")); </syntaxhighlight> Here we use the QUrl class to handle files from remote locations. Then we use the KIO library to retrieve our file. This allows us to open the file normally even if it's stored in a remote location like an FTP site. We make the following call to the <tt>[http://api.kde.org/frameworks-api/frameworks5-apidocs/kio/html/namespaceKIO.html#a17631774b47cddb0127d8a3c1fc2315c KIO::storedGet()]</tt> function with an argument for the file you wish to open or download: <syntaxhighlight lang="cpp-qt"> KIO::Job* job = KIO::storedGet(fileNameFromDialog); </syntaxhighlight> The function returns a handle to a <tt>KIO::Job</tt>, which we first connect to our <tt>downloadFinished()</tt> slot before "running" the job. <syntaxhighlight lang="cpp-qt"> connect(job, SIGNAL(result(KJob*)), this, SLOT(downloadFinished(KJob*))); job->exec(); </syntaxhighlight> The rest of the work happens in the <tt>downloadFinished()</tt> slot. First, the job is checked for errors. If it failed, we display a message box giving the error. We also make sure to clear the fileName, since the file wasn't opened successfully: <syntaxhighlight lang="cpp-qt"> KMessageBox::error(this, job->errorString()); fileName.clear(); </syntaxhighlight> Otherwise, we continue with opening the file. The data that <tt>storedGet()</tt> successfully downloaded, in this case the contents of our text file, is stored in the <tt>data</tt> member of a <tt>[http://api.kde.org/frameworks-api/frameworks5-apidocs/kio/html/classKIO_1_1StoredTransferJob.html KIO::StoredTransferJob]</tt> class. But in order to display the contents of the file at text, we must use a [http://doc.qt.io/qt-5/qtextstream.html QTextStream]. We create one by passing the the data of the <tt>StoredTransferJob</tt> to its constructor and then call its <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. <syntaxhighlight lang="cpp-qt"> KIO::StoredTransferJob* storedJob = (KIO::StoredTransferJob*)job; textArea->setPlainText(QTextStream(storedJob->data(), QIODevice::ReadOnly).readAll()); </syntaxhighlight> {{{Note|Again, for simplicity's sake, this tutorial only saves text files to local disk. When you open a remote file for viewing and try to save it, the program will behave as if you were calling Save As on a completely new file.}} <span id="Make,_Install,_and_Run"></span> == Construire, installer et exécuter == <span id="CMakeLists.txt"></span> === CMakeLists.txt === <syntaxhighlight lang="cmake"> cmake_minimum_required(VERSION 3.0) project (tutorial4) set(QT_MIN_VERSION "5.3.0") set(KF5_MIN_VERSION "5.2.0") find_package(ECM 1.0.0 REQUIRED NO_MODULE) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) include(KDEInstallDirs) include(KDECMakeSettings) include(KDECompilerSettings NO_POLICY_SCOPE) include(FeatureSummary) find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS Core # QCommandLineParser, QStringLiteral, QSaveFile, QTextStream, QByteArray Widgets # QApplication, QAction, QFileDialog ) find_package(KF5 ${KF5_MIN_VERSION} REQUIRED COMPONENTS CoreAddons # KAboutData I18n # KLocalizedString XmlGui # KXmlGuiWindow, KActionCollection TextWidgets # KTextEdit ConfigWidgets # KStandardActions WidgetsAddons # KMessageBox KIO # KIO ) feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES) set(tutorial4_SRCS main.cpp mainwindow.cpp) add_executable(tutorial4 ${tutorial4_SRCS}) target_link_libraries(tutorial4 Qt5::Widgets KF5::CoreAddons KF5::I18n KF5::XmlGui KF5::TextWidgets KF5::ConfigWidgets KF5::WidgetsAddons KF5::KIOCore ) install(TARGETS tutorial4 ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) install(FILES tutorial4ui.rc DESTINATION ${KDE_INSTALL_KXMLGUI5DIR}/tutorial4) </syntaxhighlight> Since we are now using the KIO library, we must tell CMake to link against it. We do this by passing <tt>KIO</tt> to the <tt>find_package()</tt> function and <tt>KF5::KIOCore</tt> to <tt>target_link_libraries()</tt> function. With this file, the tutorial can be built and run in the same way as tutorial 3. For more information, see tutorial 3. <syntaxhighlight lang="bash"> mkdir build && cd build cmake .. -DCMAKE_INSTALL_PREFIX=$HOME make install XDG_DATA_DIRS=$HOME/share:$XDG_DATA_DIRS $HOME/bin/tutorial4 </syntaxhighlight> <span id="Moving_On"></span> == Aller plus loin == Now you can move on to the [[Development/Tutorials/CommandLineArguments|command line arguments]] tutorial. [[Category:C++]]
Toggle limited content width