https://techbase.kde.org/api.php?action=feedcontributions&user=Ozzi&feedformat=atomKDE TechBase - User contributions [en]2024-03-28T16:48:11ZUser contributionsMediaWiki 1.40.2https://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(fi)&diff=19833Development/Tutorials/KDE4 Porting Guide (fi)2008-01-17T10:11:05Z<p>Ozzi: /* Qt4 API */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Esipuhe==<br />
Tämä perehdytys on tarkoitettu ohjelmistokehittäjille auttaakseen heitä siirtämään heidän Qt3/KDE3 ohjelmistonsa Qt4/KDE4 ympäristöön. KDE3 ohjelmien siirron ei välttämättä tarvitse olla hankala prosessi. On olemassa valmiina monia komentojonoja ja dokumentaatio lähteitä tämän helpottamiseksi.<br />
<br />
==Käsitteet==<br />
Tämän perehdytyksen ohjeissa käytetään seuraavia käsitteitä:<br />
* {{program|program}} kuvaa suoritettavaa tiedostoa, ohjelmaa<br />
* {{path|path}} kuvaa polkua<br />
* {{path|file}} kuvaa tiedostoa<br />
* $SVN on täydellinen polku paikalliseen kopioon KDE:n SVN kopiosta<br />
<br />
==CMake==<br />
KDE3 ohjelmista poiketen KDE4 ohjelmat käännetään [[Development/Tutorials/CMake (fi)| CMakea]] apuna käyttäen. Helpoin tapa siirtää "autotools system" CMakelle on käyttää apuna {{program|am2cmake}}-komentojonoa joka löytyy [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk] moduulin alta {{path|cmake/scripts}}-hakemistosta. {{program|am2cmake}}-luo, riippuen vanhan käännösjärjestelmän tiedostojen määrästä, joukon {{path|CMakeLists.txt}}-tiedostoja.<br />
<br />
Esimerkiksi, jos lähdekoodisi sijaitsee {{path|/path/to/src}}-hakemistossa, niin:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Suorita <tt> am2cmake --help</tt> tarkistaaksesi tarvitsetko <tt>--kde4</tt> valitsinta.<br />
<br />
Samasta {{path|$SVN/trunk/kde/kdesdk/scripts}}-hakemistosta löytyy myös {{program|cmakelint.pl}}-niminen työkalu jolla voit tarkistaa uusien {{path|CMakeList.txt}}-tiedostojen mahdolliset ongelmat. Käyttö:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Tai, jos tarkistat kaikki {{path|CMakeLists.txt}} lähdekoodi hakemistostasi:<br />
<code bash><br />
% cd /path/to/src<br />
% find . -name CMakeLists.txt | \<br />
xargs $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl<br />
</code><br />
<br />
==Qt4 API==<br />
<br />
Aluksi, on erittäin suositeltavaa tutustua Trolltech:n tuottamaan [http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"]-dokumenttiin, josta löytyy erittäin hyvä yleiskatsaus suuremmista muutoksista siirryttäessä Qt3:sta Qt4:n.<br />
<br />
Seuraavana löytyy [http://doc.trolltech.com/latest/porting4.html "Porting to Qt 4"]-dokumentin jossa on kerrottu hyvin yksityiskohtaisesti josta löytyy hyvin yksityiskohtaista tietoa siirrosprosessista. Sivustossa on yksityiskohtaisesti listattu luokkien ja funktioiden muutokset.<br />
<br />
Näissä dokumenteissa on esitelty Trolltech tuottama työkalu nimeltä {{program|qt3to4}}, joka on tarkoitettu yhteensopivuus funktioita apuna käyttäen helpottamaan koodin Qt osuuksien siirtämistä Qt3:sta Qt4:n. Käytä {{program|qt3to4}} seuraavasti:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile voi olla joko lähdekooditiedosto tai projektitiedosto. Jos käytät projektitiedostoa, pääte joko '.pro' tai '.pri', {{program|qt3to4}} käy läpi kaikki tiedostot jotka kuuluvat projektiin.<br />
<br />
Lisätietoja, suorita {{program|qt3to4}} '--help' valitsimen kanssa tai katso [http://doc.trolltech.com/latest/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"].<br />
<br />
Lisäksi {{module|kdesdk}} moduulissa on työkalu nimeltä {{program|remove-qt3-support.pl}}, joka etsii ja korvaa suuren osan vanhentuneita Qt3 asioita puolestasi. Aja tämä työkalu ilman valisimia lähdekoodihakemistossasi:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
Koska on mahdollista että joitain Qt3 luokkia jää vielä koodiin, varmista että lähdekoodihakemistosi juuren CMakeLists.txt tiedostossa on määritelty sekä QT3_SUPPORT että QT3_SUPPORT_WARNINGS makrot Qt otsikkotiedostoille. Esim:<br />
<code><br />
add_definitions (-DQT3_SUPPORT -DQT3_SUPPORT_WARNINGS)<br />
</code><br />
<br />
==KDE4 API==<br />
Much of the porting effort consists of simply renaming class names and header files. Since it would be rather tedious to change all these by hand, there is a handy script in the {{path|scripts/qt4}} directory of {{module|kdesdk}} called {{program|adapt-to-kde4-api.pl}}. This will scan all your files and create a {{program|diff}} output which can then be used to patch your code.<br />
<br />
Once that simple code substitution has been done, you will still have to go through your code to port to, for example, the new <tt>KAction</tt> API. Documentation about all API changes is kept in the [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] file in the {{module|kdelibs}} module.<br />
<br />
==Qt Designer UI Files==<br />
Qt designer ".ui" files created using Qt3 must be converted to the new Qt4 format. This can be done using the {{program|uic3}} program available from your Qt4 installation.<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/uic3 -convert file.ui > foo.ui<br />
% mv foo.ui file.ui<br />
</code><br />
<br />
Or, if you prefer a graphical tool, you can use Qt4's designer program<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/designer file.ui<br />
(you can save file.ui over top itself, or save to a new file)<br />
</code><br />
{{Warning|Beware, the conversion process loses any custom slots, table columns, etc. So, you may need to put some stuff back by hand.}}<br />
You should also run the {{program|fixuifiles}} program from the {{module|kdesdk}} module, it performs cleanups and sanity checks:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Instead of DCOP in KDE3, KDE4 now uses D-Bus for its interprocess communication. Porting from DCOP to D-Bus is a large topic that is covered in great detail in the [[Development/Tutorials/Porting_to_D-Bus|Porting to D-Bus tutorial]].<br />
<br />
For more information, please see all our [[Development/Tutorials#D-Bus|D-Bus tutorials]].<br />
<br />
==Icons==<br />
KDE4 uses the [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html freedesktop.org icon naming specification] as the basis for icon names. This means that both the icons that ship with KDE4 (Oxygen) as well as components in kdelibs that use icons follow this specification.<br />
<br />
Porting your app from the icon names used in KDE3 to the ones used in KDE4 is as easy as running the [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] script from the root directory of your project and follow the instructions on screen. <br />
<br />
The script automatically converts confirmable positives (e.g. uses of KIcon or KIconLoader), skips confirmable negatives and prompts for what to do with possible positives. It shows the latter with additonal context if desired and makes it a simple matter of pressing 'y' or 'n' for the possible hits to complete the porting.<br />
<br />
==Internationalization==<br />
To create your ".pot" file, copy the commands from the 'messages' rule in your projects {{path|Makefile.am}} to a shell script called {{path|Messages.sh}}. You may assume the same variables ($PREPARETIPS, $XGETTEXT, $podir, etc.) still exist, but keep in mind the differences between Makefile and shell script syntax.<br />
<br />
Also be careful that if you use the -k parameter with $XGETTEXT, you will need to explicitly list all variants that you use.<br />
<br />
For example, the 'messages' creation rule:<br />
<code><br />
messages: rc.cpp<br />
rm -f tips.cpp<br />
$(PREPARETIPS) > tips.cpp<br />
$(XGETTEXT) -ktranslate *.cpp *.h -o $(podir)/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
becomes the following {{path|Messages.sh}} script:<br />
<code bash><br />
#! /usr/bin/env bash<br />
$PREPARETIPS > tips.cpp<br />
$XGETTEXT -ktranslate:1,1t -ktranslate:1c,2,2t *.cpp *.h -o $podir/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
<br />
==Do's and Don'ts== <br />
* Do NOT use the old-style socket classes. <br />
* Do NOT use {{qt3|QPtrList}}, and in general, setAutoDelete() <br />
* Do NOT make use of raster operations. <br />
* Do NOT do code painting on widgets outside paint events. <br />
* Try not to use {{qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Prefer layouts instead. <br />
* Do NOT play with frames of groupboxes, labels, or lineedits to fake a different widget. Use the appropriate widget instead. e.g., instead of setting a label to have a sunken lineedit border, how about using a readonly {{class|KLineEdit}} instead? And instead of using a {{class|KLineEdit}} without a border for a copyable widget, use {{class|KActiveLabel}}. <br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Resources== <br />
===Documentation=== <br />
* [http://doc.trolltech.com/4.3 Qt4.3 Reference] <br />
* [http://developer.kde.org/documentation/library/svn-api.php KDE4 API Reference] <br />
* [http://www.cmake.org/HTML/Documentation.html CMake Cross Platform Make] <br />
* [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html]<br />
<br />
===Other Help=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(fi)&diff=19831Development/Tutorials/KDE4 Porting Guide (fi)2008-01-17T08:31:24Z<p>Ozzi: /* CMake */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Esipuhe==<br />
Tämä perehdytys on tarkoitettu ohjelmistokehittäjille auttaakseen heitä siirtämään heidän Qt3/KDE3 ohjelmistonsa Qt4/KDE4 ympäristöön. KDE3 ohjelmien siirron ei välttämättä tarvitse olla hankala prosessi. On olemassa valmiina monia komentojonoja ja dokumentaatio lähteitä tämän helpottamiseksi.<br />
<br />
==Käsitteet==<br />
Tämän perehdytyksen ohjeissa käytetään seuraavia käsitteitä:<br />
* {{program|program}} kuvaa suoritettavaa tiedostoa, ohjelmaa<br />
* {{path|path}} kuvaa polkua<br />
* {{path|file}} kuvaa tiedostoa<br />
* $SVN on täydellinen polku paikalliseen kopioon KDE:n SVN kopiosta<br />
<br />
==CMake==<br />
KDE3 ohjelmista poiketen KDE4 ohjelmat käännetään [[Development/Tutorials/CMake (fi)| CMakea]] apuna käyttäen. Helpoin tapa siirtää "autotools system" CMakelle on käyttää apuna {{program|am2cmake}}-komentojonoa joka löytyy [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk] moduulin alta {{path|cmake/scripts}}-hakemistosta. {{program|am2cmake}}-luo, riippuen vanhan käännösjärjestelmän tiedostojen määrästä, joukon {{path|CMakeLists.txt}}-tiedostoja.<br />
<br />
Esimerkiksi, jos lähdekoodisi sijaitsee {{path|/path/to/src}}-hakemistossa, niin:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Suorita <tt> am2cmake --help</tt> tarkistaaksesi tarvitsetko <tt>--kde4</tt> valitsinta.<br />
<br />
Samasta {{path|$SVN/trunk/kde/kdesdk/scripts}}-hakemistosta löytyy myös {{program|cmakelint.pl}}-niminen työkalu jolla voit tarkistaa uusien {{path|CMakeList.txt}}-tiedostojen mahdolliset ongelmat. Käyttö:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Tai, jos tarkistat kaikki {{path|CMakeLists.txt}} lähdekoodi hakemistostasi:<br />
<code bash><br />
% cd /path/to/src<br />
% find . -name CMakeLists.txt | \<br />
xargs $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl<br />
</code><br />
<br />
==Qt4 API==<br />
An overview of the Qt3 to Qt4 transition is provided in Trolltech's <br />
[http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"] paper. This document provides an excellent overview into the major functionality changes with Qt4 and is highly recommended.<br />
<br />
The follow-on [http://doc.trolltech.com/latest/porting4.html "Porting to Qt 4"] page gives an amazingly detailed description of the porting process, along with a list of the changes in the classes and functions.<br />
<br />
These documents describe a tool provided by Trolltech called {{program|qt3to4}} that can help port the Qt parts of your code from Qt3 to Qt4, using compatibility functions. Run {{program|qt3to4}} as follows:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile can be a source file or a project file. If you specify a project file, ending with '.pro' or '.pri', {{program|qt3to4}} will port all files specified in that project.<br />
<br />
For more information, run {{program|qt3to4}} with the "--help" option or visit <br />
the [http://doc.trolltech.com/latest/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"] page.<br />
<br />
Additionally, there is a program called {{program|remove-qt3-support.pl}} in the {{module|kdesdk}} module that will search and replace lots of deprecated Qt3 stuff for you. Simply run this program without any options in the source directory.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
Chances are that some Qt3 classes will still remain in the code, so make sure your top-level CMakeLists.txt file defines the QT3_SUPPORT and QT3_SUPPORT_WARNINGS macros for the Qt headers, like so:<br />
<code><br />
add_definitions (-DQT3_SUPPORT -DQT3_SUPPORT_WARNINGS)<br />
</code><br />
<br />
==KDE4 API==<br />
Much of the porting effort consists of simply renaming class names and header files. Since it would be rather tedious to change all these by hand, there is a handy script in the {{path|scripts/qt4}} directory of {{module|kdesdk}} called {{program|adapt-to-kde4-api.pl}}. This will scan all your files and create a {{program|diff}} output which can then be used to patch your code.<br />
<br />
Once that simple code substitution has been done, you will still have to go through your code to port to, for example, the new <tt>KAction</tt> API. Documentation about all API changes is kept in the [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] file in the {{module|kdelibs}} module.<br />
<br />
==Qt Designer UI Files==<br />
Qt designer ".ui" files created using Qt3 must be converted to the new Qt4 format. This can be done using the {{program|uic3}} program available from your Qt4 installation.<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/uic3 -convert file.ui > foo.ui<br />
% mv foo.ui file.ui<br />
</code><br />
<br />
Or, if you prefer a graphical tool, you can use Qt4's designer program<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/designer file.ui<br />
(you can save file.ui over top itself, or save to a new file)<br />
</code><br />
{{Warning|Beware, the conversion process loses any custom slots, table columns, etc. So, you may need to put some stuff back by hand.}}<br />
You should also run the {{program|fixuifiles}} program from the {{module|kdesdk}} module, it performs cleanups and sanity checks:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Instead of DCOP in KDE3, KDE4 now uses D-Bus for its interprocess communication. Porting from DCOP to D-Bus is a large topic that is covered in great detail in the [[Development/Tutorials/Porting_to_D-Bus|Porting to D-Bus tutorial]].<br />
<br />
For more information, please see all our [[Development/Tutorials#D-Bus|D-Bus tutorials]].<br />
<br />
==Icons==<br />
KDE4 uses the [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html freedesktop.org icon naming specification] as the basis for icon names. This means that both the icons that ship with KDE4 (Oxygen) as well as components in kdelibs that use icons follow this specification.<br />
<br />
Porting your app from the icon names used in KDE3 to the ones used in KDE4 is as easy as running the [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] script from the root directory of your project and follow the instructions on screen. <br />
<br />
The script automatically converts confirmable positives (e.g. uses of KIcon or KIconLoader), skips confirmable negatives and prompts for what to do with possible positives. It shows the latter with additonal context if desired and makes it a simple matter of pressing 'y' or 'n' for the possible hits to complete the porting.<br />
<br />
==Internationalization==<br />
To create your ".pot" file, copy the commands from the 'messages' rule in your projects {{path|Makefile.am}} to a shell script called {{path|Messages.sh}}. You may assume the same variables ($PREPARETIPS, $XGETTEXT, $podir, etc.) still exist, but keep in mind the differences between Makefile and shell script syntax.<br />
<br />
Also be careful that if you use the -k parameter with $XGETTEXT, you will need to explicitly list all variants that you use.<br />
<br />
For example, the 'messages' creation rule:<br />
<code><br />
messages: rc.cpp<br />
rm -f tips.cpp<br />
$(PREPARETIPS) > tips.cpp<br />
$(XGETTEXT) -ktranslate *.cpp *.h -o $(podir)/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
becomes the following {{path|Messages.sh}} script:<br />
<code bash><br />
#! /usr/bin/env bash<br />
$PREPARETIPS > tips.cpp<br />
$XGETTEXT -ktranslate:1,1t -ktranslate:1c,2,2t *.cpp *.h -o $podir/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
<br />
==Do's and Don'ts== <br />
* Do NOT use the old-style socket classes. <br />
* Do NOT use {{qt3|QPtrList}}, and in general, setAutoDelete() <br />
* Do NOT make use of raster operations. <br />
* Do NOT do code painting on widgets outside paint events. <br />
* Try not to use {{qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Prefer layouts instead. <br />
* Do NOT play with frames of groupboxes, labels, or lineedits to fake a different widget. Use the appropriate widget instead. e.g., instead of setting a label to have a sunken lineedit border, how about using a readonly {{class|KLineEdit}} instead? And instead of using a {{class|KLineEdit}} without a border for a copyable widget, use {{class|KActiveLabel}}. <br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Resources== <br />
===Documentation=== <br />
* [http://doc.trolltech.com/4.3 Qt4.3 Reference] <br />
* [http://developer.kde.org/documentation/library/svn-api.php KDE4 API Reference] <br />
* [http://www.cmake.org/HTML/Documentation.html CMake Cross Platform Make] <br />
* [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html]<br />
<br />
===Other Help=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(fi)&diff=19830Development/Tutorials/KDE4 Porting Guide (fi)2008-01-17T08:30:41Z<p>Ozzi: /* CMake */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Esipuhe==<br />
Tämä perehdytys on tarkoitettu ohjelmistokehittäjille auttaakseen heitä siirtämään heidän Qt3/KDE3 ohjelmistonsa Qt4/KDE4 ympäristöön. KDE3 ohjelmien siirron ei välttämättä tarvitse olla hankala prosessi. On olemassa valmiina monia komentojonoja ja dokumentaatio lähteitä tämän helpottamiseksi.<br />
<br />
==Käsitteet==<br />
Tämän perehdytyksen ohjeissa käytetään seuraavia käsitteitä:<br />
* {{program|program}} kuvaa suoritettavaa tiedostoa, ohjelmaa<br />
* {{path|path}} kuvaa polkua<br />
* {{path|file}} kuvaa tiedostoa<br />
* $SVN on täydellinen polku paikalliseen kopioon KDE:n SVN kopiosta<br />
<br />
==CMake==<br />
KDE3 ohjelmista poiketen KDE4 ohjelmat käännetään [[Development/Tutorials/CMake | CMakea]] apuna käyttäen. Helpoin tapa siirtää "autotools system" CMakelle on käyttää apuna {{program|am2cmake}}-komentojonoa joka löytyy [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk] moduulin alta {{path|cmake/scripts}}-hakemistosta. {{program|am2cmake}}-luo, riippuen vanhan käännösjärjestelmän tiedostojen määrästä, joukon {{path|CMakeLists.txt}}-tiedostoja.<br />
<br />
Esimerkiksi, jos lähdekoodisi sijaitsee {{path|/path/to/src}}-hakemistossa, niin:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Suorita <tt> am2cmake --help</tt> tarkistaaksesi tarvitsetko <tt>--kde4</tt> valitsinta.<br />
<br />
Samasta {{path|$SVN/trunk/kde/kdesdk/scripts}}-hakemistosta löytyy myös {{program|cmakelint.pl}}-niminen työkalu jolla voit tarkistaa uusien {{path|CMakeList.txt}}-tiedostojen mahdolliset ongelmat. Käyttö:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Tai, jos tarkistat kaikki {{path|CMakeLists.txt}} lähdekoodi hakemistostasi:<br />
<code bash><br />
% cd /path/to/src<br />
% find . -name CMakeLists.txt | \<br />
xargs $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl<br />
</code><br />
<br />
==Qt4 API==<br />
An overview of the Qt3 to Qt4 transition is provided in Trolltech's <br />
[http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"] paper. This document provides an excellent overview into the major functionality changes with Qt4 and is highly recommended.<br />
<br />
The follow-on [http://doc.trolltech.com/latest/porting4.html "Porting to Qt 4"] page gives an amazingly detailed description of the porting process, along with a list of the changes in the classes and functions.<br />
<br />
These documents describe a tool provided by Trolltech called {{program|qt3to4}} that can help port the Qt parts of your code from Qt3 to Qt4, using compatibility functions. Run {{program|qt3to4}} as follows:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile can be a source file or a project file. If you specify a project file, ending with '.pro' or '.pri', {{program|qt3to4}} will port all files specified in that project.<br />
<br />
For more information, run {{program|qt3to4}} with the "--help" option or visit <br />
the [http://doc.trolltech.com/latest/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"] page.<br />
<br />
Additionally, there is a program called {{program|remove-qt3-support.pl}} in the {{module|kdesdk}} module that will search and replace lots of deprecated Qt3 stuff for you. Simply run this program without any options in the source directory.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
Chances are that some Qt3 classes will still remain in the code, so make sure your top-level CMakeLists.txt file defines the QT3_SUPPORT and QT3_SUPPORT_WARNINGS macros for the Qt headers, like so:<br />
<code><br />
add_definitions (-DQT3_SUPPORT -DQT3_SUPPORT_WARNINGS)<br />
</code><br />
<br />
==KDE4 API==<br />
Much of the porting effort consists of simply renaming class names and header files. Since it would be rather tedious to change all these by hand, there is a handy script in the {{path|scripts/qt4}} directory of {{module|kdesdk}} called {{program|adapt-to-kde4-api.pl}}. This will scan all your files and create a {{program|diff}} output which can then be used to patch your code.<br />
<br />
Once that simple code substitution has been done, you will still have to go through your code to port to, for example, the new <tt>KAction</tt> API. Documentation about all API changes is kept in the [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] file in the {{module|kdelibs}} module.<br />
<br />
==Qt Designer UI Files==<br />
Qt designer ".ui" files created using Qt3 must be converted to the new Qt4 format. This can be done using the {{program|uic3}} program available from your Qt4 installation.<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/uic3 -convert file.ui > foo.ui<br />
% mv foo.ui file.ui<br />
</code><br />
<br />
Or, if you prefer a graphical tool, you can use Qt4's designer program<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/designer file.ui<br />
(you can save file.ui over top itself, or save to a new file)<br />
</code><br />
{{Warning|Beware, the conversion process loses any custom slots, table columns, etc. So, you may need to put some stuff back by hand.}}<br />
You should also run the {{program|fixuifiles}} program from the {{module|kdesdk}} module, it performs cleanups and sanity checks:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Instead of DCOP in KDE3, KDE4 now uses D-Bus for its interprocess communication. Porting from DCOP to D-Bus is a large topic that is covered in great detail in the [[Development/Tutorials/Porting_to_D-Bus|Porting to D-Bus tutorial]].<br />
<br />
For more information, please see all our [[Development/Tutorials#D-Bus|D-Bus tutorials]].<br />
<br />
==Icons==<br />
KDE4 uses the [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html freedesktop.org icon naming specification] as the basis for icon names. This means that both the icons that ship with KDE4 (Oxygen) as well as components in kdelibs that use icons follow this specification.<br />
<br />
Porting your app from the icon names used in KDE3 to the ones used in KDE4 is as easy as running the [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] script from the root directory of your project and follow the instructions on screen. <br />
<br />
The script automatically converts confirmable positives (e.g. uses of KIcon or KIconLoader), skips confirmable negatives and prompts for what to do with possible positives. It shows the latter with additonal context if desired and makes it a simple matter of pressing 'y' or 'n' for the possible hits to complete the porting.<br />
<br />
==Internationalization==<br />
To create your ".pot" file, copy the commands from the 'messages' rule in your projects {{path|Makefile.am}} to a shell script called {{path|Messages.sh}}. You may assume the same variables ($PREPARETIPS, $XGETTEXT, $podir, etc.) still exist, but keep in mind the differences between Makefile and shell script syntax.<br />
<br />
Also be careful that if you use the -k parameter with $XGETTEXT, you will need to explicitly list all variants that you use.<br />
<br />
For example, the 'messages' creation rule:<br />
<code><br />
messages: rc.cpp<br />
rm -f tips.cpp<br />
$(PREPARETIPS) > tips.cpp<br />
$(XGETTEXT) -ktranslate *.cpp *.h -o $(podir)/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
becomes the following {{path|Messages.sh}} script:<br />
<code bash><br />
#! /usr/bin/env bash<br />
$PREPARETIPS > tips.cpp<br />
$XGETTEXT -ktranslate:1,1t -ktranslate:1c,2,2t *.cpp *.h -o $podir/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
<br />
==Do's and Don'ts== <br />
* Do NOT use the old-style socket classes. <br />
* Do NOT use {{qt3|QPtrList}}, and in general, setAutoDelete() <br />
* Do NOT make use of raster operations. <br />
* Do NOT do code painting on widgets outside paint events. <br />
* Try not to use {{qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Prefer layouts instead. <br />
* Do NOT play with frames of groupboxes, labels, or lineedits to fake a different widget. Use the appropriate widget instead. e.g., instead of setting a label to have a sunken lineedit border, how about using a readonly {{class|KLineEdit}} instead? And instead of using a {{class|KLineEdit}} without a border for a copyable widget, use {{class|KActiveLabel}}. <br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Resources== <br />
===Documentation=== <br />
* [http://doc.trolltech.com/4.3 Qt4.3 Reference] <br />
* [http://developer.kde.org/documentation/library/svn-api.php KDE4 API Reference] <br />
* [http://www.cmake.org/HTML/Documentation.html CMake Cross Platform Make] <br />
* [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html]<br />
<br />
===Other Help=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(fi)&diff=19829Development/Tutorials/KDE4 Porting Guide (fi)2008-01-17T08:09:08Z<p>Ozzi: /* CMake */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Esipuhe==<br />
Tämä perehdytys on tarkoitettu ohjelmistokehittäjille auttaakseen heitä siirtämään heidän Qt3/KDE3 ohjelmistonsa Qt4/KDE4 ympäristöön. KDE3 ohjelmien siirron ei välttämättä tarvitse olla hankala prosessi. On olemassa valmiina monia komentojonoja ja dokumentaatio lähteitä tämän helpottamiseksi.<br />
<br />
==Käsitteet==<br />
Tämän perehdytyksen ohjeissa käytetään seuraavia käsitteitä:<br />
* {{program|program}} kuvaa suoritettavaa tiedostoa, ohjelmaa<br />
* {{path|path}} kuvaa polkua<br />
* {{path|file}} kuvaa tiedostoa<br />
* $SVN on täydellinen polku paikalliseen kopioon KDE:n SVN kopiosta<br />
<br />
==CMake==<br />
KDE3:a poiketen KDE4 ohjelmat käännetään [[Development/Tutorials/CMake | CMakea]] apuna käyttäen. Helpoin tapa siirtää "autotools system" CMakelle on käyttää apuna {{program|am2cmake}}-komentojonoa joka löytyy [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk] moduulin alta {{path|cmake/scripts}}-hakemistosta. {{program|am2cmake}}-luo, riippuen vanhan käännösjärjestelmän tiedostojen määrästä, joukon {{path|CMakeLists.txt}}-tiedostoja.<br />
<br />
Esimerkiksi, jos lähdekoodisi sijaitsee {{path|/path/to/src}}-hakemistossa, niin:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Suorita <tt> am2cmake --help</tt> tarkistaaksesi tarvitsetko <tt>--kde4</tt> valitsinta.<br />
<br />
Samasta {{path|$SVN/trunk/kde/kdesdk/scripts}}-hakemistosta löytyy myös {{program|cmakelint.pl}}-niminen työkalu jolla voit tarkistaa uusien {{path|CMakeList.txt}}-tiedostojen mahdolliset ongelmat. Käyttö:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Tai, jos tarkistat kaikki {{path|CMakeLists.txt}} lähdekoodi hakemistostasi:<br />
<code bash><br />
% cd /path/to/src<br />
% find . -name CMakeLists.txt | \<br />
xargs $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl<br />
</code><br />
<br />
==Qt4 API==<br />
An overview of the Qt3 to Qt4 transition is provided in Trolltech's <br />
[http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"] paper. This document provides an excellent overview into the major functionality changes with Qt4 and is highly recommended.<br />
<br />
The follow-on [http://doc.trolltech.com/latest/porting4.html "Porting to Qt 4"] page gives an amazingly detailed description of the porting process, along with a list of the changes in the classes and functions.<br />
<br />
These documents describe a tool provided by Trolltech called {{program|qt3to4}} that can help port the Qt parts of your code from Qt3 to Qt4, using compatibility functions. Run {{program|qt3to4}} as follows:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile can be a source file or a project file. If you specify a project file, ending with '.pro' or '.pri', {{program|qt3to4}} will port all files specified in that project.<br />
<br />
For more information, run {{program|qt3to4}} with the "--help" option or visit <br />
the [http://doc.trolltech.com/latest/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"] page.<br />
<br />
Additionally, there is a program called {{program|remove-qt3-support.pl}} in the {{module|kdesdk}} module that will search and replace lots of deprecated Qt3 stuff for you. Simply run this program without any options in the source directory.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
Chances are that some Qt3 classes will still remain in the code, so make sure your top-level CMakeLists.txt file defines the QT3_SUPPORT and QT3_SUPPORT_WARNINGS macros for the Qt headers, like so:<br />
<code><br />
add_definitions (-DQT3_SUPPORT -DQT3_SUPPORT_WARNINGS)<br />
</code><br />
<br />
==KDE4 API==<br />
Much of the porting effort consists of simply renaming class names and header files. Since it would be rather tedious to change all these by hand, there is a handy script in the {{path|scripts/qt4}} directory of {{module|kdesdk}} called {{program|adapt-to-kde4-api.pl}}. This will scan all your files and create a {{program|diff}} output which can then be used to patch your code.<br />
<br />
Once that simple code substitution has been done, you will still have to go through your code to port to, for example, the new <tt>KAction</tt> API. Documentation about all API changes is kept in the [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] file in the {{module|kdelibs}} module.<br />
<br />
==Qt Designer UI Files==<br />
Qt designer ".ui" files created using Qt3 must be converted to the new Qt4 format. This can be done using the {{program|uic3}} program available from your Qt4 installation.<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/uic3 -convert file.ui > foo.ui<br />
% mv foo.ui file.ui<br />
</code><br />
<br />
Or, if you prefer a graphical tool, you can use Qt4's designer program<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/designer file.ui<br />
(you can save file.ui over top itself, or save to a new file)<br />
</code><br />
{{Warning|Beware, the conversion process loses any custom slots, table columns, etc. So, you may need to put some stuff back by hand.}}<br />
You should also run the {{program|fixuifiles}} program from the {{module|kdesdk}} module, it performs cleanups and sanity checks:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Instead of DCOP in KDE3, KDE4 now uses D-Bus for its interprocess communication. Porting from DCOP to D-Bus is a large topic that is covered in great detail in the [[Development/Tutorials/Porting_to_D-Bus|Porting to D-Bus tutorial]].<br />
<br />
For more information, please see all our [[Development/Tutorials#D-Bus|D-Bus tutorials]].<br />
<br />
==Icons==<br />
KDE4 uses the [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html freedesktop.org icon naming specification] as the basis for icon names. This means that both the icons that ship with KDE4 (Oxygen) as well as components in kdelibs that use icons follow this specification.<br />
<br />
Porting your app from the icon names used in KDE3 to the ones used in KDE4 is as easy as running the [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] script from the root directory of your project and follow the instructions on screen. <br />
<br />
The script automatically converts confirmable positives (e.g. uses of KIcon or KIconLoader), skips confirmable negatives and prompts for what to do with possible positives. It shows the latter with additonal context if desired and makes it a simple matter of pressing 'y' or 'n' for the possible hits to complete the porting.<br />
<br />
==Internationalization==<br />
To create your ".pot" file, copy the commands from the 'messages' rule in your projects {{path|Makefile.am}} to a shell script called {{path|Messages.sh}}. You may assume the same variables ($PREPARETIPS, $XGETTEXT, $podir, etc.) still exist, but keep in mind the differences between Makefile and shell script syntax.<br />
<br />
Also be careful that if you use the -k parameter with $XGETTEXT, you will need to explicitly list all variants that you use.<br />
<br />
For example, the 'messages' creation rule:<br />
<code><br />
messages: rc.cpp<br />
rm -f tips.cpp<br />
$(PREPARETIPS) > tips.cpp<br />
$(XGETTEXT) -ktranslate *.cpp *.h -o $(podir)/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
becomes the following {{path|Messages.sh}} script:<br />
<code bash><br />
#! /usr/bin/env bash<br />
$PREPARETIPS > tips.cpp<br />
$XGETTEXT -ktranslate:1,1t -ktranslate:1c,2,2t *.cpp *.h -o $podir/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
<br />
==Do's and Don'ts== <br />
* Do NOT use the old-style socket classes. <br />
* Do NOT use {{qt3|QPtrList}}, and in general, setAutoDelete() <br />
* Do NOT make use of raster operations. <br />
* Do NOT do code painting on widgets outside paint events. <br />
* Try not to use {{qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Prefer layouts instead. <br />
* Do NOT play with frames of groupboxes, labels, or lineedits to fake a different widget. Use the appropriate widget instead. e.g., instead of setting a label to have a sunken lineedit border, how about using a readonly {{class|KLineEdit}} instead? And instead of using a {{class|KLineEdit}} without a border for a copyable widget, use {{class|KActiveLabel}}. <br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Resources== <br />
===Documentation=== <br />
* [http://doc.trolltech.com/4.3 Qt4.3 Reference] <br />
* [http://developer.kde.org/documentation/library/svn-api.php KDE4 API Reference] <br />
* [http://www.cmake.org/HTML/Documentation.html CMake Cross Platform Make] <br />
* [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html]<br />
<br />
===Other Help=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(fi)&diff=19826Development/Tutorials/KDE4 Porting Guide (fi)2008-01-17T07:22:03Z<p>Ozzi: /* Käsitteet */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Esipuhe==<br />
Tämä perehdytys on tarkoitettu ohjelmistokehittäjille auttaakseen heitä siirtämään heidän Qt3/KDE3 ohjelmistonsa Qt4/KDE4 ympäristöön. KDE3 ohjelmien siirron ei välttämättä tarvitse olla hankala prosessi. On olemassa valmiina monia komentojonoja ja dokumentaatio lähteitä tämän helpottamiseksi.<br />
<br />
==Käsitteet==<br />
Tämän perehdytyksen ohjeissa käytetään seuraavia käsitteitä:<br />
* {{program|program}} kuvaa suoritettavaa tiedostoa, ohjelmaa<br />
* {{path|path}} kuvaa polkua<br />
* {{path|file}} kuvaa tiedostoa<br />
* $SVN on täydellinen polku paikalliseen kopioon KDE:n SVN kopiosta<br />
<br />
==CMake==<br />
Unlike KDE3, KDE4 applications will be built with the help of [[Development/Tutorials/CMake | CMake]]. The easiest way to port your autotools system to CMake is with the help of the {{program|am2cmake}} script which can be found in the {{path|cmake/scripts}} directory of the [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk] module. This will create a series of {{path|CMakeLists.txt}} files alongside your old buildsystem files.<br />
<br />
For example, if your source code is located in {{path|/path/to/src}} then:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Run <tt> am2cmake --help</tt> to check whether you need the <tt>--kde4</tt> flag.<br />
<br />
There is also a tool that looks in your resulting {{path|CMakeList.txt}} files for potential problems. This tool called {{program|cmakelint.pl}} is located in {{path|$SVN/trunk/kde/kdesdk/scripts}}. Use it like so:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Or, to run it over your entire source directory:<br />
<code bash><br />
% cd /path/to/src<br />
% find . -name CMakeLists.txt | \<br />
xargs $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl<br />
</code><br />
<br />
==Qt4 API==<br />
An overview of the Qt3 to Qt4 transition is provided in Trolltech's <br />
[http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"] paper. This document provides an excellent overview into the major functionality changes with Qt4 and is highly recommended.<br />
<br />
The follow-on [http://doc.trolltech.com/latest/porting4.html "Porting to Qt 4"] page gives an amazingly detailed description of the porting process, along with a list of the changes in the classes and functions.<br />
<br />
These documents describe a tool provided by Trolltech called {{program|qt3to4}} that can help port the Qt parts of your code from Qt3 to Qt4, using compatibility functions. Run {{program|qt3to4}} as follows:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile can be a source file or a project file. If you specify a project file, ending with '.pro' or '.pri', {{program|qt3to4}} will port all files specified in that project.<br />
<br />
For more information, run {{program|qt3to4}} with the "--help" option or visit <br />
the [http://doc.trolltech.com/latest/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"] page.<br />
<br />
Additionally, there is a program called {{program|remove-qt3-support.pl}} in the {{module|kdesdk}} module that will search and replace lots of deprecated Qt3 stuff for you. Simply run this program without any options in the source directory.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
Chances are that some Qt3 classes will still remain in the code, so make sure your top-level CMakeLists.txt file defines the QT3_SUPPORT and QT3_SUPPORT_WARNINGS macros for the Qt headers, like so:<br />
<code><br />
add_definitions (-DQT3_SUPPORT -DQT3_SUPPORT_WARNINGS)<br />
</code><br />
<br />
==KDE4 API==<br />
Much of the porting effort consists of simply renaming class names and header files. Since it would be rather tedious to change all these by hand, there is a handy script in the {{path|scripts/qt4}} directory of {{module|kdesdk}} called {{program|adapt-to-kde4-api.pl}}. This will scan all your files and create a {{program|diff}} output which can then be used to patch your code.<br />
<br />
Once that simple code substitution has been done, you will still have to go through your code to port to, for example, the new <tt>KAction</tt> API. Documentation about all API changes is kept in the [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] file in the {{module|kdelibs}} module.<br />
<br />
==Qt Designer UI Files==<br />
Qt designer ".ui" files created using Qt3 must be converted to the new Qt4 format. This can be done using the {{program|uic3}} program available from your Qt4 installation.<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/uic3 -convert file.ui > foo.ui<br />
% mv foo.ui file.ui<br />
</code><br />
<br />
Or, if you prefer a graphical tool, you can use Qt4's designer program<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/designer file.ui<br />
(you can save file.ui over top itself, or save to a new file)<br />
</code><br />
{{Warning|Beware, the conversion process loses any custom slots, table columns, etc. So, you may need to put some stuff back by hand.}}<br />
You should also run the {{program|fixuifiles}} program from the {{module|kdesdk}} module, it performs cleanups and sanity checks:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Instead of DCOP in KDE3, KDE4 now uses D-Bus for its interprocess communication. Porting from DCOP to D-Bus is a large topic that is covered in great detail in the [[Development/Tutorials/Porting_to_D-Bus|Porting to D-Bus tutorial]].<br />
<br />
For more information, please see all our [[Development/Tutorials#D-Bus|D-Bus tutorials]].<br />
<br />
==Icons==<br />
KDE4 uses the [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html freedesktop.org icon naming specification] as the basis for icon names. This means that both the icons that ship with KDE4 (Oxygen) as well as components in kdelibs that use icons follow this specification.<br />
<br />
Porting your app from the icon names used in KDE3 to the ones used in KDE4 is as easy as running the [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] script from the root directory of your project and follow the instructions on screen. <br />
<br />
The script automatically converts confirmable positives (e.g. uses of KIcon or KIconLoader), skips confirmable negatives and prompts for what to do with possible positives. It shows the latter with additonal context if desired and makes it a simple matter of pressing 'y' or 'n' for the possible hits to complete the porting.<br />
<br />
==Internationalization==<br />
To create your ".pot" file, copy the commands from the 'messages' rule in your projects {{path|Makefile.am}} to a shell script called {{path|Messages.sh}}. You may assume the same variables ($PREPARETIPS, $XGETTEXT, $podir, etc.) still exist, but keep in mind the differences between Makefile and shell script syntax.<br />
<br />
Also be careful that if you use the -k parameter with $XGETTEXT, you will need to explicitly list all variants that you use.<br />
<br />
For example, the 'messages' creation rule:<br />
<code><br />
messages: rc.cpp<br />
rm -f tips.cpp<br />
$(PREPARETIPS) > tips.cpp<br />
$(XGETTEXT) -ktranslate *.cpp *.h -o $(podir)/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
becomes the following {{path|Messages.sh}} script:<br />
<code bash><br />
#! /usr/bin/env bash<br />
$PREPARETIPS > tips.cpp<br />
$XGETTEXT -ktranslate:1,1t -ktranslate:1c,2,2t *.cpp *.h -o $podir/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
<br />
==Do's and Don'ts== <br />
* Do NOT use the old-style socket classes. <br />
* Do NOT use {{qt3|QPtrList}}, and in general, setAutoDelete() <br />
* Do NOT make use of raster operations. <br />
* Do NOT do code painting on widgets outside paint events. <br />
* Try not to use {{qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Prefer layouts instead. <br />
* Do NOT play with frames of groupboxes, labels, or lineedits to fake a different widget. Use the appropriate widget instead. e.g., instead of setting a label to have a sunken lineedit border, how about using a readonly {{class|KLineEdit}} instead? And instead of using a {{class|KLineEdit}} without a border for a copyable widget, use {{class|KActiveLabel}}. <br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Resources== <br />
===Documentation=== <br />
* [http://doc.trolltech.com/4.3 Qt4.3 Reference] <br />
* [http://developer.kde.org/documentation/library/svn-api.php KDE4 API Reference] <br />
* [http://www.cmake.org/HTML/Documentation.html CMake Cross Platform Make] <br />
* [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html]<br />
<br />
===Other Help=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(fi)&diff=19825Development/Tutorials/KDE4 Porting Guide (fi)2008-01-17T07:21:47Z<p>Ozzi: /* Conventions */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Esipuhe==<br />
Tämä perehdytys on tarkoitettu ohjelmistokehittäjille auttaakseen heitä siirtämään heidän Qt3/KDE3 ohjelmistonsa Qt4/KDE4 ympäristöön. KDE3 ohjelmien siirron ei välttämättä tarvitse olla hankala prosessi. On olemassa valmiina monia komentojonoja ja dokumentaatio lähteitä tämän helpottamiseksi.<br />
<br />
==Käsitteet==<br />
Tämän perehdytyksen ohjeissa käytetään seuraavia lyhenteitä:<br />
* {{program|program}} kuvaa suoritettavaa tiedostoa, ohjelmaa<br />
* {{path|path}} kuvaa polkua<br />
* {{path|file}} kuvaa tiedostoa<br />
* $SVN on täydellinen polku paikalliseen kopioon KDE:n SVN kopiosta<br />
<br />
==CMake==<br />
Unlike KDE3, KDE4 applications will be built with the help of [[Development/Tutorials/CMake | CMake]]. The easiest way to port your autotools system to CMake is with the help of the {{program|am2cmake}} script which can be found in the {{path|cmake/scripts}} directory of the [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk] module. This will create a series of {{path|CMakeLists.txt}} files alongside your old buildsystem files.<br />
<br />
For example, if your source code is located in {{path|/path/to/src}} then:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Run <tt> am2cmake --help</tt> to check whether you need the <tt>--kde4</tt> flag.<br />
<br />
There is also a tool that looks in your resulting {{path|CMakeList.txt}} files for potential problems. This tool called {{program|cmakelint.pl}} is located in {{path|$SVN/trunk/kde/kdesdk/scripts}}. Use it like so:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Or, to run it over your entire source directory:<br />
<code bash><br />
% cd /path/to/src<br />
% find . -name CMakeLists.txt | \<br />
xargs $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl<br />
</code><br />
<br />
==Qt4 API==<br />
An overview of the Qt3 to Qt4 transition is provided in Trolltech's <br />
[http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"] paper. This document provides an excellent overview into the major functionality changes with Qt4 and is highly recommended.<br />
<br />
The follow-on [http://doc.trolltech.com/latest/porting4.html "Porting to Qt 4"] page gives an amazingly detailed description of the porting process, along with a list of the changes in the classes and functions.<br />
<br />
These documents describe a tool provided by Trolltech called {{program|qt3to4}} that can help port the Qt parts of your code from Qt3 to Qt4, using compatibility functions. Run {{program|qt3to4}} as follows:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile can be a source file or a project file. If you specify a project file, ending with '.pro' or '.pri', {{program|qt3to4}} will port all files specified in that project.<br />
<br />
For more information, run {{program|qt3to4}} with the "--help" option or visit <br />
the [http://doc.trolltech.com/latest/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"] page.<br />
<br />
Additionally, there is a program called {{program|remove-qt3-support.pl}} in the {{module|kdesdk}} module that will search and replace lots of deprecated Qt3 stuff for you. Simply run this program without any options in the source directory.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
Chances are that some Qt3 classes will still remain in the code, so make sure your top-level CMakeLists.txt file defines the QT3_SUPPORT and QT3_SUPPORT_WARNINGS macros for the Qt headers, like so:<br />
<code><br />
add_definitions (-DQT3_SUPPORT -DQT3_SUPPORT_WARNINGS)<br />
</code><br />
<br />
==KDE4 API==<br />
Much of the porting effort consists of simply renaming class names and header files. Since it would be rather tedious to change all these by hand, there is a handy script in the {{path|scripts/qt4}} directory of {{module|kdesdk}} called {{program|adapt-to-kde4-api.pl}}. This will scan all your files and create a {{program|diff}} output which can then be used to patch your code.<br />
<br />
Once that simple code substitution has been done, you will still have to go through your code to port to, for example, the new <tt>KAction</tt> API. Documentation about all API changes is kept in the [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] file in the {{module|kdelibs}} module.<br />
<br />
==Qt Designer UI Files==<br />
Qt designer ".ui" files created using Qt3 must be converted to the new Qt4 format. This can be done using the {{program|uic3}} program available from your Qt4 installation.<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/uic3 -convert file.ui > foo.ui<br />
% mv foo.ui file.ui<br />
</code><br />
<br />
Or, if you prefer a graphical tool, you can use Qt4's designer program<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/designer file.ui<br />
(you can save file.ui over top itself, or save to a new file)<br />
</code><br />
{{Warning|Beware, the conversion process loses any custom slots, table columns, etc. So, you may need to put some stuff back by hand.}}<br />
You should also run the {{program|fixuifiles}} program from the {{module|kdesdk}} module, it performs cleanups and sanity checks:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Instead of DCOP in KDE3, KDE4 now uses D-Bus for its interprocess communication. Porting from DCOP to D-Bus is a large topic that is covered in great detail in the [[Development/Tutorials/Porting_to_D-Bus|Porting to D-Bus tutorial]].<br />
<br />
For more information, please see all our [[Development/Tutorials#D-Bus|D-Bus tutorials]].<br />
<br />
==Icons==<br />
KDE4 uses the [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html freedesktop.org icon naming specification] as the basis for icon names. This means that both the icons that ship with KDE4 (Oxygen) as well as components in kdelibs that use icons follow this specification.<br />
<br />
Porting your app from the icon names used in KDE3 to the ones used in KDE4 is as easy as running the [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] script from the root directory of your project and follow the instructions on screen. <br />
<br />
The script automatically converts confirmable positives (e.g. uses of KIcon or KIconLoader), skips confirmable negatives and prompts for what to do with possible positives. It shows the latter with additonal context if desired and makes it a simple matter of pressing 'y' or 'n' for the possible hits to complete the porting.<br />
<br />
==Internationalization==<br />
To create your ".pot" file, copy the commands from the 'messages' rule in your projects {{path|Makefile.am}} to a shell script called {{path|Messages.sh}}. You may assume the same variables ($PREPARETIPS, $XGETTEXT, $podir, etc.) still exist, but keep in mind the differences between Makefile and shell script syntax.<br />
<br />
Also be careful that if you use the -k parameter with $XGETTEXT, you will need to explicitly list all variants that you use.<br />
<br />
For example, the 'messages' creation rule:<br />
<code><br />
messages: rc.cpp<br />
rm -f tips.cpp<br />
$(PREPARETIPS) > tips.cpp<br />
$(XGETTEXT) -ktranslate *.cpp *.h -o $(podir)/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
becomes the following {{path|Messages.sh}} script:<br />
<code bash><br />
#! /usr/bin/env bash<br />
$PREPARETIPS > tips.cpp<br />
$XGETTEXT -ktranslate:1,1t -ktranslate:1c,2,2t *.cpp *.h -o $podir/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
<br />
==Do's and Don'ts== <br />
* Do NOT use the old-style socket classes. <br />
* Do NOT use {{qt3|QPtrList}}, and in general, setAutoDelete() <br />
* Do NOT make use of raster operations. <br />
* Do NOT do code painting on widgets outside paint events. <br />
* Try not to use {{qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Prefer layouts instead. <br />
* Do NOT play with frames of groupboxes, labels, or lineedits to fake a different widget. Use the appropriate widget instead. e.g., instead of setting a label to have a sunken lineedit border, how about using a readonly {{class|KLineEdit}} instead? And instead of using a {{class|KLineEdit}} without a border for a copyable widget, use {{class|KActiveLabel}}. <br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Resources== <br />
===Documentation=== <br />
* [http://doc.trolltech.com/4.3 Qt4.3 Reference] <br />
* [http://developer.kde.org/documentation/library/svn-api.php KDE4 API Reference] <br />
* [http://www.cmake.org/HTML/Documentation.html CMake Cross Platform Make] <br />
* [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html]<br />
<br />
===Other Help=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials_(fi)&diff=19824Development/Tutorials (fi)2008-01-17T07:17:30Z<p>Ozzi: /* Perusteet */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials}}<br />
<br />
Täältä löytyvät ohjeet ovat nopein tapa saada selville, mitä KDE tekee ja kuinka se tekee. T&auml;ss&auml; on luettelo t&auml;ll&auml; hetkell&auml; k&auml;ytett&auml;vist&auml; opastusohjeista <b>KDE4:lle</b>. Materiaali KDE3:lle ja KDE2:lle löytyy t&auml;m&auml;n sivun lopussa.<br />
<br />
== Perehdytys KDE 4 ohjelmointiin ==<br />
Kiinnostaako sovellusten kehitt&auml;minen KDE 4:lle? T&auml;m&auml; ohjesarja on tarkoitettu KDE-ohjelmointia aloitteleville.<br />
;[[Development/Tutorials/First program (fi)|Hei maailma!]]<br />
:''Perehdytt&auml;minen KDE4-ohjelmoinnin alkeisiin''<br />
<br />
;[[Development/Tutorials/Using KXmlGuiWindow (fi)|Main-ikkunan luonti]]<br />
:''T&auml;m&auml; ohje opettaa t&auml;rkeimm&auml;n taikatempun: main-ikkunan tekemisen.''<br />
<br />
;[[Development/Tutorials/Using KActions (fi)|KActions ja XMLGUI]]<br />
:''Kuinka valikkoihin ja ty&ouml;kalupalkkeihin lis&auml;t&auml;&auml;n toimintoja.''<br />
<br />
;[[Development/Tutorials/Saving_and_loading (fi)|Tallettaminen ja Avaaminen]]<br />
:''Kuinka tallentaa tiedostot sekä kuinka avata ne.''<br />
<br />
== Perusteet ==<br />
;[[Development/Tutorials/KDE4 Porting Guide (fi)|Sovelluksen siirto]]<br />
:''Opaste sovellusten siirtoon Qt3/KDE3:sta Qt4/KDE4:een''<br />
<br />
;[[Development/Tutorials/CMake_(fi)|CMake-perehdytys]]<br />
:''Kuinka k&auml;ytt&auml;&auml; KDE4:n k&auml;ytt&auml;m&auml;&auml; CMake-rakentamisj&auml;rjestelm&auml;&auml;.''<br />
<br />
;[[Development/Tutorials/Common Programming Mistakes|Yleiset ohjelmointivirheet]]<br />
:''Tässä esitellään yleisiä virheitä, joita tehd&auml;&auml;n Qt- ja KDE-sovellusten kehitt&auml;misen aikana ja opastetaan välttämään ne..''<br />
<br />
;[[Development/Tutorials/Using Qt Designer_(fi)|K&auml;ytet&auml;&auml;n Qt Designer-ohjelmaa k&auml;ytt&ouml;liittymien luomiseen]]<br />
:''Kuinka UI-tiedostoja luodaan Qt Designer -ohjelmalla ja kuinka ne integroidaan KDE-ohjelmaan.''<br />
<br />
== Testaus ja virheenj&auml;ljitys ==<br />
<br />
;[[Development/Tutorials/Debugging|Sovelluksesi virheenj&auml;ljitys]]<br />
:''Vihjeit&auml;, ty&ouml;kaluja ja tekniikoita sovellettavaksi virheiden jäljittämiseksi KDE-sovelluksesta''<br />
<br />
;[[Development/Tutorials/Unittests|Kirjoitetaan yksikk&ouml;testej&auml; Qt4:lle ja KDE4:lle QTestLib-ohjelmalla]] ([http://developer.kde.org/documentation/tutorials/writingunittests/writingunittests.html Alkuper&auml;inen linkki])<br />
:''[mailto:bradh@frogmouth.net Brad Hards]in opas, joka esittää kuinka kirjoittaa yksikk&ouml;testej&auml; k&auml;ytt&auml;en QTestLib-kehyst&auml;. Opas perustuu esimerkkeihin, ja sitä kehitetään yhä.''<br />
<br />
;[[Development/Tutorials/Code_Checking|Puoliautomaattinen tapa havaita koodivirheet]]<br />
:''Tekniikoita, joita k&auml;ytet&auml;&auml;n virheiden havaitsemiseen KDE-koodissa''<br />
<br />
== Konfiguraatiotietojen hallinta KConfig-ohjelmalla ==<br />
;[[Development/Tutorials/KConfig|KConfig-perehdytys]]<br />
:''Yleiskatsaus KConfig-luokista ja kuinka niit&auml; k&auml;ytet&auml;&auml;n sovelluskoodissasi''<br />
<br />
;[[Development/Tutorials/Using KConfig XT|KConfig XT-k&auml;ytt&ouml;]]<br />
:''Opastusohjelma siit&auml; kuinka k&auml;ytet&auml;n tehokkaasti KConfig XT-kehyst&auml;.''<br />
<br />
;[[Development/Tutorials/Updating KConfig Files|KConfig-tiedostojen p&auml;ivitys]]<br />
:''Opastus päivitysskriptin kirjoittamiseksi. Päivitysskripti pitää sovelluksesi asetustiedostot yhdenmukaisena jo olemassa olevien asetustiedostojen kanssa''<br />
<br />
== Palvelut: Sovellukset ja lis&auml;osat ==<br />
;[[Development/Tutorials/Services/Introduction|Services-palvelukehysperehdytys]]<br />
:''Yleiskuva Services-palvelukehyksest&auml; KDE:ssa ja mit&auml; se tarjoaa sovelluskehitt&auml;j&auml;lle. Kattaa j&auml;rjestelm&auml;konfiguraatiov&auml;limuistin (SyCoCa), l&auml;hdedatatiedostot ja mit&auml; indeksoituja tietoja voidaan k&auml;ytt&auml;&auml;.''<br />
<br />
;[[Development/Tutorials/Services/Traders|Services-palvelujen l&ouml;yt&auml;minen k&auml;ytt&auml;en Trader-kyselyj&auml;]]<br />
:''Kuinka l&ouml;yt&auml;&auml; palveluja, kuten lis&auml;osat tai mime-tyypit, jotka on indeksoitu SyCoCa:ssa k&auml;ytt&auml;en Trader-kyselysyntaksia''<br />
<br />
;[[Development/Tutorials/Services/Plugins|Luodaan ja ladataan lis&auml;osia k&auml;ytt&auml;en KService-palvelua]]<br />
:''Opi määrittelemään lis&auml;osatyyppej&auml;, l&ouml;ydet&auml;&auml;n asennettuja lis&auml;osia (mukaan lukien kolmansien osapuolien lis&auml;osat) ja lataa ne helpolla tavalla ja siirett&auml;v&auml;ss&auml; muodossa KService-palvelua k&auml;ytt&auml;en.''<br />
<br />
== Lokalisointi ==<br />
;[[Development/Tutorials/Localization/Unicode|Unicode-perehdytys]]<br />
:''Perehdytys Unicode-merkist&ouml;&ouml;n sekä Unicode-datan käsittelyyn KDE-sovelluksissa.''<br />
<br />
; [[Development/Tutorials/Localization/i18n|Sovellusten kirjoittaminen lokalisointi mieless&auml;]]<br />
:''T&auml;m&auml; opas kertoo, mit&auml; lokalisointi on, miksi se on t&auml;rke&auml;&auml; ja kuinka taataan, ett&auml; sovelluksesi on valmis lokalisoitavaksi. V&auml;ltt&auml;m&auml;t&ouml;ntä luettavaa kaikille sovelluskehitt&auml;jille.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Mistakes|Yleisten lokalisoitinkuoppien v&auml;ltt&auml;minen]]<br />
:''Monet yleiset virheet est&auml;v&auml;t sovellusten oikean lokalisoinnin. Selvit&auml; t&auml;st&auml; oppaasta mit&auml; nämä virheet ovat, ja kuinka vältät ne.''<br />
<br />
; [[Development/Tutorials/Localization/Building KDE's l10n Module|KDE:n lokalisointimoduulin rakentaminen]]<br />
:''Tämän oppaan avulla opit rakentamaan ja asentamaan kielituen KDE:n lokalisointi(l10n)moduulista, mikä on hyv&auml; ajatus KDE-pääsovellusten kanssa työskennellessä. Tekem&auml;ll&auml; niin voit testata sovellustasi toisella kielell&auml; ja paikantaa ongelma-alueet.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Build Systems|Sis&auml;llyt&auml; i18n rakentamisj&auml;rjestelm&auml;&auml;n]]<br />
:''Kun sovelluksesi on vihdoin valmis lokalisoitavaksi, seuraava vaihe on taata, ett&auml; k&auml;&auml;nn&ouml;stiedostot rakennetaan automaattisesti ja pidet&auml;&auml;n ajan tasalla. T&auml;m&auml; ohje kattaa v&auml;ltt&auml;tt&ouml;m&auml;t CMakeFiles.txt-lis&auml;kset samoin kuin jakeluprosessin, jonka tuloksena ovat sovelluksesi sanomaluettelot.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Challenges|Yleiset i18n-haasteet ja -ratkaisut]]<br />
:''Tämä opas käsittelee yleisiä lokalisointiongelmia: käsikirjojen kääntämistä, vanhentuneiden .po-tiedostojen yhdistelemistä ja käsittelemistä, versiojäädytyksiä, muilla kielillä kuin englanti koodaamista, riippumattomien julkaisujen luomista, sekä sovellusten siirtämistä KDE-moduulien välillä.''<br />
<br />
; [[Development/Tutorials/Localization/i18n_Semantics|Semanttiset sanomamerkinn&auml;t]]<br />
:''Yhdenmukaisen esityksen takaamiseksi ja sanomien paremman merkityksen ymm&auml;rt&auml;miseksi sovelluksissa voidaan liitt&auml;&auml; sanomiin semanttinen merkint&auml; k&auml;ytt&auml;en KUIT-j&auml;rjestelm&auml;&auml;. T&auml;m&auml; opas esittää, kuinka t&auml;m&auml; j&auml;rjestelm&auml; toimii.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Krazy|Automatisoitu i18n-kooditarkistus]]<br />
:''Krazy-kooditarkistin etsii KDE:n koodia ja ilmoittaa yleisist&auml; i18n-erehdyksist&auml;.''<br />
<br />
== Dokumentaatio ==<br />
<br />
;[[Development/Tutorials/API_Documentation|API-dokumentaatio]]<br />
:''T&auml;m&auml; opas esittää, kuinka API dokumentoidaan oikein.''<br />
<br />
;[[Development/Tutorials/Man_Pages|Man-sivut]]<br />
:''Kirjoitetaan ja luodaan käsikirjasivuja.''<br />
<br />
== Sovellusautomaatio ja skriptaus ==<br />
<br />
=== D-Bus ===<br />
; [[Development/Tutorials/D-Bus/Introduction|D-Bus-perehdytys]]<br />
:''Suoraan etenev&auml; perehdytt&auml;minen ydinkonsepteista D-Bus:ssa sovelluskehitt&auml;j&auml;n n&auml;k&ouml;kulmasta, t&auml;m&auml; ohje esittää, mit&auml; D-Bus on ja kuinka sovelluksen voivat k&auml;ytt&auml;&auml; sit&auml;.''<br />
; [[Development/Tutorials/D-Bus/Accessing Interfaces|Haetaan D-Bus rajapintoja]]<br />
:''Vaiheittain etenev&auml; opas D-Bus-metodien kutsumisesta ja kytkeytymisest&auml; D-Bus-signaaleihin k&auml;ytt&auml;en QtDBus-v&auml;yl&auml;&auml;.''<br />
; [[Development/Tutorials/D-Bus/Intermediate_D-Bus|Intermediate D-Bus]]<br />
:''Tips to make use of QtDBus when faced with problematic real-world interfaces.''<br />
; [[Development/Tutorials/D-Bus/Creating Interfaces|Luodaan D-Bus-rajapintoja]]<br />
:''Learn how to expose functionality in your application by creating and using custom D-Bus interfaces. Covers generating the XML descriptions, instantiating interfaces at run time and setting up the build system with CMake.''<br />
; [[Development/Tutorials/D-Bus/Autostart Services|D-Bus-automaattik&auml;ynnistyspalvelut]]<br />
:''Turn your application into a D-Bus autostart service with this tutorial. This D-Bus feature, also known as "D-Bus service activation", will ensure that even when your application isn't running that D-Bus calls made to it will work by relying on the D-Bus daemon itself to start your app if and when needed.''<br />
; [[Development/Tutorials/Porting_to_D-Bus|Porting from DCOP to D-Bus]]<br />
: ''Port your applications from DCOP to D-Bus with this handy guide.''<br />
<br />
=== Konqueror ===<br />
; [[Development/Tutorials/Creating Konqueror Service Menus|Luodaan Konqueror-palveluvalikoita]]<br />
:''Tämä ohje näyttää, kuinka luodaan mime-tyyppikohtaisia toimintoja näytettäväksi Konquerorin asiayhteysvalikossa (tunnetaan myös nimellä "palveluvalikot").''<br />
<br />
=== Kross ===<br />
; [[Development/Tutorials/Kross/Introduction|Kross-perehdytys]]<br />
:''Perehdytys Kross-skriptauskehykseen.''<br />
<br />
; [[Development/Tutorials/Kross/Hello_World|Hei maailma!]]<br />
:''Ensimmäinen sovellus toimivalla kross-koodilla.''<br />
<br />
; [[Development/Tutorials/Kross/Connecting_Signals_and_slots_in_Kross|Yhdistetään signaaleja ja Slots Kross:ssa]]<br />
:''Yksinkertainen demo-ohjelma objektien signaalien kytkemistä skriptisloteilla''<br />
<br />
; [[Development/Tutorials/Kross/Scripts-as-Plugins|Skriptit Kross-lisäosina]]<br />
:''Tämä ohje opastaa vaihe vaiheelta integroimaan skriptejä KDE-sovelluksen lisäosiksi.''<br />
<br />
=== KOffice ===<br />
; [[Development/Tutorials/KOffice Overview|KOffice-yleiskuvaus]]<br />
:''Tämä dokumentti esittää erilaisten KOffice-liitännäisten yleiskuvauksen ja kertoo, mikä on kunkin käyttötarkoitus ja erityisvahvuus.'' Jos olet aloittelija KOffice-lisäosien kohdalla, kannattaa aloittaa tästä.<br />
<br />
; [[Development/Tutorials/Write a Flake Plugin|Luodaan KOffice Flake-lisäosia]]<br />
:''Tämä opas näyttää, kuinka Koffice-sovelluksiin rakennetaan lisäosia, joiden avulla voidaan ODF-dokumentteihin upottaa sisältöä Flaken avulla.''<br />
<br />
; [[Development/Tutorials/KWord Scripting|KWord-skriptaus]]<br />
:''Tämä opas opettaa kehittämään KWord-skriptejä Pythonilla, Rubylla tai JavaScriptillä käyttäen Krossia.''<br />
<br />
; [[Development/Tutorials/KSpread Scripting|KSpread-skriptaus]]<br />
:''Tämä opas opettaa kehittämään KSpread-skriptejä Pythonilla, Rubylla tai JavaScriptillä käyttäen Krossia.''<br />
<br />
; [[Development/Tutorials/Krita Scripting|Krita-skriptaus]]<br />
:''Tämä opas opettaa kehittämään Krita-skriptejä Pythonilla, Rubylla tai JavaScriptillä käyttäen Krossia.''<br />
<br />
=== SuperKaramba ===<br />
; [[Development/Tutorials/SuperKaramba|SuperKaramba-opastusohje]]<br />
:''Tämä opastusohje tarjoaa SuperKaramba-yleiskuvan, teematiedostot ja Python-, Ruby- ja JavaScript-skriptauksen.''<br />
<br />
== Haku ja metadata ==<br />
<br />
=== Strigi ===<br />
<br />
; [[Development/Tutorials/Writing file analyzers|Tiedostoanalysaattorien kirjoittaminen]]<br />
:''Tiedostoanalysaattorit poimivat dataa tiedostosta näytettäväksi tiedostovalintaikkunoissa ja tiedostonhallintaohjelmissa. Tällä tavalla kerättyä dataa käytetään myös etsintään tiedostoille. KDE4 sallii useiden analysaattoreiden käytön per tiedostotyyppi. Tämä opas esittää, kuinka voit kirjoittaa uusia analysaattoreita.''<br />
<br />
=== Nepomuk ===<br />
<br />
; [[Development/Tutorials/Metadata/KMetaData first steps|Nepomuk ensi vaiheet]]<br />
:''Nepomuk on KDE-kirjasto, joka tarjoaa helpon pääsyn metadataan [http://nepomuk-kde.semanticdesktop.org Nepomuk-KDE]-järjestelmässä. Opi kuinka saat sovelluksesi luomaan ja lukemaan metadataa käyttäen Nepomuk-järjestelmää.''<br />
<br />
== Laitteistotietoisuus (Solid) ==<br />
<br />
;[[Development/Tutorials/Solid_Tutorials|Solid-perehdytys]]<br />
:''Perehdytys Solid-laitteiston havaitsemis- ja vuorovaikutusjärjestelmän käyttöön KDE-sovelluksissa.''<br />
<br />
;[[Development/Tutorials/Solid_Network_Tutorial|Tietoverkkotietojen haku]]<br />
:''Kuinka Solid-järjestelmää käytetään tietoverkkotietojen hakemiseen''<br />
<br />
== Multimedia (Phonon) ==<br />
<br />
;[[Development/Tutorials/Phonon/Introduction|Phonon]]<br />
:''Kuinka käynnistetään multimedia-API:lla''<br />
<br />
== Plasma ==<br />
<br />
;[[Development/Tutorials/Plasma/GettingStarted|Ensimmäinen plasmoidisi]]<br />
:''Luo ensimmäinen Plasma-käyttöliittymäkomponenttisi eli plasmoidi, käyttäen C++ -kieltä, SVG-taustaa, kuvaketta ja tekstiä.''<br />
<br />
;[[Development/Tutorials/Plasma/DataEngines|Kirjoitetaan DataEngine-rajapinta]]<br />
:''DataEngine-rajapinnat tarjoavat vakioidun rajapinnan eri data-lähteisiin käytettäväksi visualisoinneille. Opi mitä DataEngine-rajapinta on ja kuinka oma rajapinta kirjoitetaan.''<br />
<br />
;[[Development/Tutorials/Plasma/UsingDataEngines|Käytetään DataEngine-rajapintoja Plasmoideissa]]<br />
:''DataEngine-rajapinnalla on mahdollista hakea dataa näytölle yksinkertaisella ja vakioidulla tavalla. Tämä opas esittää, kuinka DataEngine-rajapintoja käytetään tähän tarkoitukseen Plasmoideissa.''<br />
<br />
;[[Development/Tutorials/Plasma/AbstractRunner|Luodaan Runners-lisäosia]]<br />
:''Runners-lisäosat tarjoavat toimintaperustaisen hakutoiminnon Plasma-työtilan "suorita komento"-valintaikkunassa. Mikä tahansa sovellus, joka linkitetään libplasma-kirjastoon, voi käyttää näitä lisäosia.''<br />
<br />
== Kate / Kwrite ==<br />
<br />
;[[Development/Tutorials/Kate/KTextEditor Plugins|Kuinka aloitetaan KTextEditor-lis&auml;osakehitys]]<br />
:''Luo ensimm&auml;inen KTextEditor-lis&auml;osasi''<br />
<br />
==Tulostus==<br />
<br />
;[[Development/Tutorials/Printing Hello World|Hei maailma!]]<br />
:''Perehdytys KDE-tulostusj&auml;rjestelm&auml;&auml;n''<br />
<br />
;[[Development/Tutorials/Printing Print Dialog|Tulostusviestiruutu]]<br />
:''Kuinka k&auml;ytet&auml;&auml;n KDE-tulostusviestiruutua''<br />
<br />
== Hae uutta kuumaa kamaa ==<br />
; [[Development/Tutorials/Introduction to Get Hot New Stuff|Johdatus uuden kuuman matskun hakemiseen]]<br />
:''Johdatus käyttäjäystävälliseen tietoverkkopäivitysjärjestelmään, joka sallii KDE-sovellusten noutaa uutta sovellusdataa ajoaikaisesti käyttäjäystävällisellä tavalla.''<br />
<br />
;[[Development/Tutorials/KNewStuffSecure|Suojattu KNewStuff-verkko]] ([http://developer.kde.org/documentation/tutorials/knewstuffsecure/index.html Alkuperäinen linkki])<br />
:''Opastusohje näyttää, kuinka jakaa resursseja suojatulla tavalla (KDE 3.4 ja myöhemmät versiot).'' Laatija Andr&#225;s Mantia &lt;amantia@kde.org&gt;.<br />
<br />
== Nopea sovelluskehitys ==<br />
<br />
=== Python ===<br />
<br />
;[[Development/Tutorials/Python introduction to signals and slots|101 Johdatus signaaleihin ja väleihin]]<br />
:''Yksinkertainen johdatus Qt-signaali- ja väliarkkitehtuuriin.''<br />
<br />
=== Ruby ===<br />
<br />
;[http://developer.kde.org/language-bindings/ruby/kde3tutorial/index.html KDE Ruby Korundum opastusohje]<br />
:''Antonio Larrosa Jim&eacute;nez:n kirjoittama Ruby-versio Richard Dalen kirjoittamasta KDE-perehdytyksest&auml;. Katso [http://developer.kde.org/language-bindings/ruby/index.html Ruby-kehitt&auml;jien nurkkaus] Qt-opastusohjeille ja muille tiedoille.''<br />
<br />
;[[Development/Tutorials/Qt4_Ruby_Tutorial|Qt4 Ruby-opas]]<br />
:''Trolltech:n kuuluisa alustava Qt-opas muunnettuna Ruby-perehdytykseksi.''<br />
<br />
=== Komentotulkki ===<br />
<br />
;[[Development/Tutorials/Shell_Scripting_with_KDE_Dialogs|KDE-valintaikkunoita käyttävät komentotulkkiskriptit]] ([http://developer.kde.org/documentation/tutorials/kdialog/t1.html Alkuperäinen linkki]) <br />
:''[mailto:bradh@frogmouth.net Brad Hards]:in kirjoittama opas, joka kuvaa kuinka KDE-valintaikkunoita käytetään komentotulkkikripteissä kdialogin avulla.''<br />
<br />
== Muita opastusohjeita ==<br />
<br />
=== KDE Games-kirjaston k&auml;ytt&ouml; ===<br />
;[[Development/Tutorials/Games/KStandardGameAction| KStandardGameAction]]<br />
:''Käytetään libkdegames-kirjastoa, jotta pelisi sopisi kdegames-standardiin''<br />
;[[Development/Tutorials/Games/Highscores| Parhaat pisteet]]<br />
:''Toteutetaan yksinkertainen "parhaat pisteet"-taulukko peliisi''<br />
;[[Development/Tutorials/Games/Theme Selector| Teemavalitsin]]<br />
:''Käytetään libkdegames-kirjaston teemavalitsin valintaikkunaa''<br />
<br />
=== 2D-tulostus (KPlotWidget) ===<br />
;[[Development/Tutorials/KPlotWidget|Using the KDE data-plotting widget]]<br />
:''This tutorial introduces KPlotWidget, which is used for 2-D data plotting. It includes information on simple usage of the widget (including adding and modifying data sets, and customizing the plot axes and labels), and advanced customization (including extending the widget through sub-classing).''<br />
<br />
=== Oikeinkirjoitus- ja kielioppitarkistus (Sonnet) ===<br />
;[[Development/Tutorials/Sonnet/SonnetTutorial|Oikeinkirjoitus- ja kielioppitarkistuksen lis&auml;&auml;minen KDE-sovelluksiin]]<br />
:''T&auml;m&auml; opastusohje esittelee Sonnet-ohjelman ja sen käytön KDE-sovelluksesi kielen korjaamiseen. Sonnet-ohjelman lis&auml;ominaisuudet kuvaillaan erillisess&auml; oppaassa.''<br />
<br />
=== Pixmap-v&auml;limuisti (KPixmapCache) ===<br />
;[[Development/Tutorials/KPixmapCache|KDE pixmap-v&auml;limuistin k&auml;ytt&ouml;]]<br />
:''T&auml;m&auml; opastusohje n&auml;ytt&auml;&auml; kuinka KPixmapCache:lla sijoitetaan SVG-yksikk&ouml;jen ja muun datan luomia pixmap-kuvia KDE-v&auml;limuistiin.''<br />
<br />
== KDE2- ja KDE3-materiaalit ==<br />
<br />
;[[Development/Tutorials/KDE3|KDE3-opastusohjeet]]<br />
:''N&auml;m&auml; ohjeet kattavat KDE3-aiheet.''<br />
<br />
;[[Development/Tutorials/KDE2|KDE2-opastusohjeet]]<br />
:''N&auml;m&auml; ohjeet kattavat KDE2-aiheet''<br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(fi)&diff=19823Development/Tutorials/KDE4 Porting Guide (fi)2008-01-17T07:17:04Z<p>Ozzi: Tästä se lähtee..</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Esipuhe==<br />
Tämä perehdytys on tarkoitettu ohjelmistokehittäjille auttaakseen heitä siirtämään heidän Qt3/KDE3 ohjelmistonsa Qt4/KDE4 ympäristöön. KDE3 ohjelmien siirron ei välttämättä tarvitse olla hankala prosessi. On olemassa valmiina monia komentojonoja ja dokumentaatio lähteitä tämän helpottamiseksi.<br />
<br />
==Conventions==<br />
For the instructions in this tutorial we use the following shorthand:<br />
* {{program|program}} refers to an executable program<br />
* {{path|path}} refers to a path<br />
* {{path|file}} refers to a file<br />
* $SVN is the fullpath to the location of your KDE subversion checkout<br />
<br />
==CMake==<br />
Unlike KDE3, KDE4 applications will be built with the help of [[Development/Tutorials/CMake | CMake]]. The easiest way to port your autotools system to CMake is with the help of the {{program|am2cmake}} script which can be found in the {{path|cmake/scripts}} directory of the [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk] module. This will create a series of {{path|CMakeLists.txt}} files alongside your old buildsystem files.<br />
<br />
For example, if your source code is located in {{path|/path/to/src}} then:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Run <tt> am2cmake --help</tt> to check whether you need the <tt>--kde4</tt> flag.<br />
<br />
There is also a tool that looks in your resulting {{path|CMakeList.txt}} files for potential problems. This tool called {{program|cmakelint.pl}} is located in {{path|$SVN/trunk/kde/kdesdk/scripts}}. Use it like so:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Or, to run it over your entire source directory:<br />
<code bash><br />
% cd /path/to/src<br />
% find . -name CMakeLists.txt | \<br />
xargs $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl<br />
</code><br />
<br />
==Qt4 API==<br />
An overview of the Qt3 to Qt4 transition is provided in Trolltech's <br />
[http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"] paper. This document provides an excellent overview into the major functionality changes with Qt4 and is highly recommended.<br />
<br />
The follow-on [http://doc.trolltech.com/latest/porting4.html "Porting to Qt 4"] page gives an amazingly detailed description of the porting process, along with a list of the changes in the classes and functions.<br />
<br />
These documents describe a tool provided by Trolltech called {{program|qt3to4}} that can help port the Qt parts of your code from Qt3 to Qt4, using compatibility functions. Run {{program|qt3to4}} as follows:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile can be a source file or a project file. If you specify a project file, ending with '.pro' or '.pri', {{program|qt3to4}} will port all files specified in that project.<br />
<br />
For more information, run {{program|qt3to4}} with the "--help" option or visit <br />
the [http://doc.trolltech.com/latest/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"] page.<br />
<br />
Additionally, there is a program called {{program|remove-qt3-support.pl}} in the {{module|kdesdk}} module that will search and replace lots of deprecated Qt3 stuff for you. Simply run this program without any options in the source directory.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
Chances are that some Qt3 classes will still remain in the code, so make sure your top-level CMakeLists.txt file defines the QT3_SUPPORT and QT3_SUPPORT_WARNINGS macros for the Qt headers, like so:<br />
<code><br />
add_definitions (-DQT3_SUPPORT -DQT3_SUPPORT_WARNINGS)<br />
</code><br />
<br />
==KDE4 API==<br />
Much of the porting effort consists of simply renaming class names and header files. Since it would be rather tedious to change all these by hand, there is a handy script in the {{path|scripts/qt4}} directory of {{module|kdesdk}} called {{program|adapt-to-kde4-api.pl}}. This will scan all your files and create a {{program|diff}} output which can then be used to patch your code.<br />
<br />
Once that simple code substitution has been done, you will still have to go through your code to port to, for example, the new <tt>KAction</tt> API. Documentation about all API changes is kept in the [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] file in the {{module|kdelibs}} module.<br />
<br />
==Qt Designer UI Files==<br />
Qt designer ".ui" files created using Qt3 must be converted to the new Qt4 format. This can be done using the {{program|uic3}} program available from your Qt4 installation.<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/uic3 -convert file.ui > foo.ui<br />
% mv foo.ui file.ui<br />
</code><br />
<br />
Or, if you prefer a graphical tool, you can use Qt4's designer program<br />
<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/designer file.ui<br />
(you can save file.ui over top itself, or save to a new file)<br />
</code><br />
{{Warning|Beware, the conversion process loses any custom slots, table columns, etc. So, you may need to put some stuff back by hand.}}<br />
You should also run the {{program|fixuifiles}} program from the {{module|kdesdk}} module, it performs cleanups and sanity checks:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Instead of DCOP in KDE3, KDE4 now uses D-Bus for its interprocess communication. Porting from DCOP to D-Bus is a large topic that is covered in great detail in the [[Development/Tutorials/Porting_to_D-Bus|Porting to D-Bus tutorial]].<br />
<br />
For more information, please see all our [[Development/Tutorials#D-Bus|D-Bus tutorials]].<br />
<br />
==Icons==<br />
KDE4 uses the [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html freedesktop.org icon naming specification] as the basis for icon names. This means that both the icons that ship with KDE4 (Oxygen) as well as components in kdelibs that use icons follow this specification.<br />
<br />
Porting your app from the icon names used in KDE3 to the ones used in KDE4 is as easy as running the [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] script from the root directory of your project and follow the instructions on screen. <br />
<br />
The script automatically converts confirmable positives (e.g. uses of KIcon or KIconLoader), skips confirmable negatives and prompts for what to do with possible positives. It shows the latter with additonal context if desired and makes it a simple matter of pressing 'y' or 'n' for the possible hits to complete the porting.<br />
<br />
==Internationalization==<br />
To create your ".pot" file, copy the commands from the 'messages' rule in your projects {{path|Makefile.am}} to a shell script called {{path|Messages.sh}}. You may assume the same variables ($PREPARETIPS, $XGETTEXT, $podir, etc.) still exist, but keep in mind the differences between Makefile and shell script syntax.<br />
<br />
Also be careful that if you use the -k parameter with $XGETTEXT, you will need to explicitly list all variants that you use.<br />
<br />
For example, the 'messages' creation rule:<br />
<code><br />
messages: rc.cpp<br />
rm -f tips.cpp<br />
$(PREPARETIPS) > tips.cpp<br />
$(XGETTEXT) -ktranslate *.cpp *.h -o $(podir)/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
becomes the following {{path|Messages.sh}} script:<br />
<code bash><br />
#! /usr/bin/env bash<br />
$PREPARETIPS > tips.cpp<br />
$XGETTEXT -ktranslate:1,1t -ktranslate:1c,2,2t *.cpp *.h -o $podir/kmail.pot<br />
rm -f tips.cpp<br />
</code><br />
<br />
==Do's and Don'ts== <br />
* Do NOT use the old-style socket classes. <br />
* Do NOT use {{qt3|QPtrList}}, and in general, setAutoDelete() <br />
* Do NOT make use of raster operations. <br />
* Do NOT do code painting on widgets outside paint events. <br />
* Try not to use {{qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Prefer layouts instead. <br />
* Do NOT play with frames of groupboxes, labels, or lineedits to fake a different widget. Use the appropriate widget instead. e.g., instead of setting a label to have a sunken lineedit border, how about using a readonly {{class|KLineEdit}} instead? And instead of using a {{class|KLineEdit}} without a border for a copyable widget, use {{class|KActiveLabel}}. <br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Resources== <br />
===Documentation=== <br />
* [http://doc.trolltech.com/4.3 Qt4.3 Reference] <br />
* [http://developer.kde.org/documentation/library/svn-api.php KDE4 API Reference] <br />
* [http://www.cmake.org/HTML/Documentation.html CMake Cross Platform Make] <br />
* [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html]<br />
<br />
===Other Help=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19822Development/Tutorials/Saving and loading (fi)2008-01-17T07:02:23Z<p>Ozzi: /* Moving On */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> // *uusi*<br />
#include <KMessageBox> //*uusi*<br />
#include <KIO/NetAccess> //*uusi*<br />
#include <KSaveFile> //*uusi*<br />
#include <QTextStream> //*uusi*<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //*uusi*<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //*uusi*<br />
<br />
setupGUI();<br />
}<br />
<br />
// * uutta tästä eteenpäin *<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
Tämä on muuten identtinen <tt>tutorial3ui.rc</tt> kanssa, paitsi <tt>nimi</tt> on muutettu 'tutorial4':ksi. Koska kaikki uudet toiminnot ovat <tt>KStandardAction</tt>:ta jotka KDE osaa automaattisesti käsitellä, tähän tiedostoon ei tarvitse lisätä mitään.<br />
<br />
==Selvitys==<br />
<br />
Selvitetään nyt hieman koodia joka tekee avaamisen sekä ja tallettamisen. Kaikki tarvittava on sijoitettu <tt>mainwindow.cpp</tt>-tiedostoon.<br />
<br />
Ensimmäisenä, rivillä 16, meidän pitää lisätä<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
<tt>MainWindow</tt>:n muodostajaan. Tällä varmistetaan että tiedoston nimi on tyhjä aloitettaessa.<br />
<br />
===Toimintojen lisääminen===<br />
<br />
Ensinnäkin meidän pitää lisätä liittymä ohjelman ulkopuolelle, jotta käyttäjät voivat kertoa ohjelmalle avataanko vai talletetaanko tiedosto. Samaan tapaan kuin Perehdytyksessä 3, <tt>lopeta</tt>-toiminnon kanssa, käytämme tähänkin tarkoitukseen <tt>KStandardActions</tt>:a riveillä 37-47. Kaikki uudet toiminnot on kytketty sopiviin sloteihin jotka esittelimme otsikkotiedostossa riveillä 20-24. <br />
<br />
===Uusi asiakirja===<br />
<br />
Ensimmäisenä funktio jonka loimme on <tt>newFile()</tt>-funktio.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<tt>fileName.clear()</tt> asettaa <tt>fileName</tt> (QString) merkkijonon tyhjäksi kuvaamaan että tätä tiedostoa ei ole olemassa talletettuna minnekkään. <br />
<tt>textArea->clear()</tt> tyhjentää tekstialueen käyttäen samaa <tt>KAction</tt>:n <tt>clear</tt>-funktiota johon kytkimme Tyhjennä-toimionnon Perehdytyksessä 3.<br />
<br />
===Tiedoston tallettaminen===<br />
<br />
====saveFileAs(QString)====<br />
<br />
Siirrymme nyt ensimmäiseen tiedostoja käsittelevään koodiin. Seuraavaksi syvennymme funktioon jonka tehtävänä on tallentaa tekstialueen sisältö paramterinä annetulla tiedostonimellä. KDE tarjoaa turvalliseen tiedoston tallettamiseen Qt:n {{qt|QFile}}:a johdetun {{class|KSaveFile}}-luokan.<br />
<br />
Funktion prototyyppi on:<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
Seuraavaksi luomme <tt>KSaveFile</tt>-objektin ja avaamme sen<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
Nyt kun meillä on tiedosto johon kirjoittaa, meidän pitää muotoilla teksti alueen sisältö sellaiseen muotoon joka on mahdollista kirjoittaa tiedostoon. Tätä tarkoitusta varten luomme {{qt|QByteArray}}:n johon syötämme tekstialueen sisällön tekstinä, ilman muotoiluja, seuraavasti: <br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
Nyt meillä on <tt>KSaveFile::write()</tt>:n kanssa käytettävä <tt>QByteArray</tt> calmiina. Normaalin <tt>QFile</tt>:n käyttäminen olisi myös mahdollista, ja se tallettaisi muutokset välittömästi, mutta jos tällöin tapahtuisi jokin virhe tallentamisen aikana, tulisi tiedostosta viallinen. Tästä syystä <tt>KSaveFile</tt> luo ensin väliaikaisen tiedoston, ja vasta kun kutsutaan <tt>KSaveFile::finalize()</tt>-funktiota, luodaan varsinainen tiedosto.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Ja lopuksi asetetaan <tt>MainWindows</tt>:n <tt>fileName</tt> osoittamaan tiedostoon jonka juuri tallensimme:<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
Tähän funktioon on yhdistetty <tt>saveAs</tt>(Tallenna nimellä) toiminto. Tämä funktio kutsuu <tt>saveFileAs(QString)</tt>-funktiota jolle lähetetään parametrinä <br />
<tt>{{class|KFileDialog}}::[http://api.kde.org/4.0-api/kdelibs-apidocs/kio/html/classKFileDialog.html#8891356c249c5911e1ab15cc2739a89b getSaveFileName()]</tt>:n palauttama tiedoston nimi.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
Tässä kohdassa käytämme ensimmäisen kerran KIO-kirjastoa. {{class|KFileDialog}}-luokka tarjoaa meille joukon funktioita joita kaikki KDE ohjelmat käyttävät yleisten tiedostovalikoiden näyttämiseen. <tt>KFileDialog::getSaveFileName()</tt>-funktion kutsuminen tuo esille tiedostovalikon jossa käyttäjä voi valita tai vaihtaa tiedoston nimeä tai tallennussijaintia. Funktio palauttaa täydellisen tiedoston nimen, jonka me välitimme <tt>saveFileAs(QString)</tt>-funktiolle.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
Tässä funktiossa ei ole mitään erityistä tai uutta. Tässä vain päätellään, näytetäänkö tallennusvalikko vai ei. Jos <tt>fileName</tt> ei ole tyhjä, tallennetaan tiedosto mitään kysymättä nimellä joka on sijoitettuna <tt>fileName</tt>:n kutsumalla saveFileAs(QString)-funktiota, muuten kutsutaan yllä olevaa saveFileAs()-funktiota.<br />
<br />
===Tiedoston avaaminen===<br />
<br />
Lopulta olemme valmiit tarkastelemaan tiedoston avaamista levyltä. Kaikki koodi tätä tarkoitusta varten on sijoitettu <tt>MainWindow::openFile()</tt>-funktioon.<br />
<br />
Ensin meidän pitää kysyä käyttäjältä, mikä tiedosto halutaan avattavan. Tätä tarkoitusta varten me käytämme toista <tt>KFileDialog</tt>-funktiota, <tt>getOpenFileName()</tt>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
Seuraavaksi käytämme KIO-kirjastoa tiedoston avaamiseen. KIO-kirjasto antaa meille mahdollisuuden avata tiedosto QFilen avulla, paikalliselta levyltä tai etäkoneelta, vaikkapa FTP:n yli. Tiedoston avaamiseksi käytämme {{class|NetAccess}}:n <tt>download()</tt>-funktiota:<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
Ensimmäinen argumentti on avattavan tiedoston nimi. Toinen on QString, joka tiedoston hakemisen jälkeen, sisältää väliaikaisen tiedoston sijainnin. Tämän <tt>tmpFile</tt>:n kanssa jatkamme tästä eteenpäin.<br />
<br />
Funktio palauttaa boolen arvon <tt>tosi</tt> tai <tt>epätosi</tt>, riippuen onnistuiko tiedoston siirto. Jos tiedoston haku epäonnistui, näytetään virheilmoitus:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Muussa tapauksessa jatketaan tiedoston avaamista.<br />
<br />
Luomme uuden QFile:n välittämällä sen muodostajaan <tt>NetAccess::download()</tt>:n luoman väliaikaistiedoston jonka jälkeen avataan se kirjoitussuojattuna:<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
Tuodaksemme avaamamme tiedoston sisällön ruudulle näkyviin, tarvitsee meidän käyttää {{class|QTextStream}}-luokkaa. {{class|QTextStream}}:n muodostajalle välitämme äsken avaamamme tiedoston (QFile file) ja kutsumme QFile:n <tt>readAll()</tt>-funktiota saadaksemme tekstin tiedostosta. Seuraavaksi välitämme tämän kaiken meidän tekstialueen <tt>setPlainText()</tt>-funktiolle:<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
Talletetaan avatun tiedoston nimi(polkuineen):<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
<br />
Ja lopuksi poistetaan <tt>NetAccess::download()</tt>:n luoma väliaikaistiedosto:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Käännä, Asenna ja Suorita==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
Koska otimme nyt KIO-kirjaston käyttöön, tarvitsee meidän kertoa CMakelle että linkittäjän tarvitsee ottaa myös tämä mukaan. Tätä varten lisäämme <tt>target_link_libraries()</tt>-funktioon tiedon <tt>${KDE4_KIO_LIBS}</tt>.<br />
<br />
=== Komennot ===<br />
Itse käännös, asennus ja suoritus menee samalla tavalla kuin Perehdytyksessä 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Seuraavaksi==<br />
Seuraavana perehdytys: [[Development/Tutorials/KCmdLineArgs|Komentoriviparametrit.]] (keskeneräinen, englanniksi)<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19821Development/Tutorials/Saving and loading (fi)2008-01-17T06:58:22Z<p>Ozzi: /* Make, Install And Run */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> // *uusi*<br />
#include <KMessageBox> //*uusi*<br />
#include <KIO/NetAccess> //*uusi*<br />
#include <KSaveFile> //*uusi*<br />
#include <QTextStream> //*uusi*<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //*uusi*<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //*uusi*<br />
<br />
setupGUI();<br />
}<br />
<br />
// * uutta tästä eteenpäin *<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
Tämä on muuten identtinen <tt>tutorial3ui.rc</tt> kanssa, paitsi <tt>nimi</tt> on muutettu 'tutorial4':ksi. Koska kaikki uudet toiminnot ovat <tt>KStandardAction</tt>:ta jotka KDE osaa automaattisesti käsitellä, tähän tiedostoon ei tarvitse lisätä mitään.<br />
<br />
==Selvitys==<br />
<br />
Selvitetään nyt hieman koodia joka tekee avaamisen sekä ja tallettamisen. Kaikki tarvittava on sijoitettu <tt>mainwindow.cpp</tt>-tiedostoon.<br />
<br />
Ensimmäisenä, rivillä 16, meidän pitää lisätä<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
<tt>MainWindow</tt>:n muodostajaan. Tällä varmistetaan että tiedoston nimi on tyhjä aloitettaessa.<br />
<br />
===Toimintojen lisääminen===<br />
<br />
Ensinnäkin meidän pitää lisätä liittymä ohjelman ulkopuolelle, jotta käyttäjät voivat kertoa ohjelmalle avataanko vai talletetaanko tiedosto. Samaan tapaan kuin Perehdytyksessä 3, <tt>lopeta</tt>-toiminnon kanssa, käytämme tähänkin tarkoitukseen <tt>KStandardActions</tt>:a riveillä 37-47. Kaikki uudet toiminnot on kytketty sopiviin sloteihin jotka esittelimme otsikkotiedostossa riveillä 20-24. <br />
<br />
===Uusi asiakirja===<br />
<br />
Ensimmäisenä funktio jonka loimme on <tt>newFile()</tt>-funktio.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<tt>fileName.clear()</tt> asettaa <tt>fileName</tt> (QString) merkkijonon tyhjäksi kuvaamaan että tätä tiedostoa ei ole olemassa talletettuna minnekkään. <br />
<tt>textArea->clear()</tt> tyhjentää tekstialueen käyttäen samaa <tt>KAction</tt>:n <tt>clear</tt>-funktiota johon kytkimme Tyhjennä-toimionnon Perehdytyksessä 3.<br />
<br />
===Tiedoston tallettaminen===<br />
<br />
====saveFileAs(QString)====<br />
<br />
Siirrymme nyt ensimmäiseen tiedostoja käsittelevään koodiin. Seuraavaksi syvennymme funktioon jonka tehtävänä on tallentaa tekstialueen sisältö paramterinä annetulla tiedostonimellä. KDE tarjoaa turvalliseen tiedoston tallettamiseen Qt:n {{qt|QFile}}:a johdetun {{class|KSaveFile}}-luokan.<br />
<br />
Funktion prototyyppi on:<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
Seuraavaksi luomme <tt>KSaveFile</tt>-objektin ja avaamme sen<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
Nyt kun meillä on tiedosto johon kirjoittaa, meidän pitää muotoilla teksti alueen sisältö sellaiseen muotoon joka on mahdollista kirjoittaa tiedostoon. Tätä tarkoitusta varten luomme {{qt|QByteArray}}:n johon syötämme tekstialueen sisällön tekstinä, ilman muotoiluja, seuraavasti: <br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
Nyt meillä on <tt>KSaveFile::write()</tt>:n kanssa käytettävä <tt>QByteArray</tt> calmiina. Normaalin <tt>QFile</tt>:n käyttäminen olisi myös mahdollista, ja se tallettaisi muutokset välittömästi, mutta jos tällöin tapahtuisi jokin virhe tallentamisen aikana, tulisi tiedostosta viallinen. Tästä syystä <tt>KSaveFile</tt> luo ensin väliaikaisen tiedoston, ja vasta kun kutsutaan <tt>KSaveFile::finalize()</tt>-funktiota, luodaan varsinainen tiedosto.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Ja lopuksi asetetaan <tt>MainWindows</tt>:n <tt>fileName</tt> osoittamaan tiedostoon jonka juuri tallensimme:<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
Tähän funktioon on yhdistetty <tt>saveAs</tt>(Tallenna nimellä) toiminto. Tämä funktio kutsuu <tt>saveFileAs(QString)</tt>-funktiota jolle lähetetään parametrinä <br />
<tt>{{class|KFileDialog}}::[http://api.kde.org/4.0-api/kdelibs-apidocs/kio/html/classKFileDialog.html#8891356c249c5911e1ab15cc2739a89b getSaveFileName()]</tt>:n palauttama tiedoston nimi.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
Tässä kohdassa käytämme ensimmäisen kerran KIO-kirjastoa. {{class|KFileDialog}}-luokka tarjoaa meille joukon funktioita joita kaikki KDE ohjelmat käyttävät yleisten tiedostovalikoiden näyttämiseen. <tt>KFileDialog::getSaveFileName()</tt>-funktion kutsuminen tuo esille tiedostovalikon jossa käyttäjä voi valita tai vaihtaa tiedoston nimeä tai tallennussijaintia. Funktio palauttaa täydellisen tiedoston nimen, jonka me välitimme <tt>saveFileAs(QString)</tt>-funktiolle.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
Tässä funktiossa ei ole mitään erityistä tai uutta. Tässä vain päätellään, näytetäänkö tallennusvalikko vai ei. Jos <tt>fileName</tt> ei ole tyhjä, tallennetaan tiedosto mitään kysymättä nimellä joka on sijoitettuna <tt>fileName</tt>:n kutsumalla saveFileAs(QString)-funktiota, muuten kutsutaan yllä olevaa saveFileAs()-funktiota.<br />
<br />
===Tiedoston avaaminen===<br />
<br />
Lopulta olemme valmiit tarkastelemaan tiedoston avaamista levyltä. Kaikki koodi tätä tarkoitusta varten on sijoitettu <tt>MainWindow::openFile()</tt>-funktioon.<br />
<br />
Ensin meidän pitää kysyä käyttäjältä, mikä tiedosto halutaan avattavan. Tätä tarkoitusta varten me käytämme toista <tt>KFileDialog</tt>-funktiota, <tt>getOpenFileName()</tt>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
Seuraavaksi käytämme KIO-kirjastoa tiedoston avaamiseen. KIO-kirjasto antaa meille mahdollisuuden avata tiedosto QFilen avulla, paikalliselta levyltä tai etäkoneelta, vaikkapa FTP:n yli. Tiedoston avaamiseksi käytämme {{class|NetAccess}}:n <tt>download()</tt>-funktiota:<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
Ensimmäinen argumentti on avattavan tiedoston nimi. Toinen on QString, joka tiedoston hakemisen jälkeen, sisältää väliaikaisen tiedoston sijainnin. Tämän <tt>tmpFile</tt>:n kanssa jatkamme tästä eteenpäin.<br />
<br />
Funktio palauttaa boolen arvon <tt>tosi</tt> tai <tt>epätosi</tt>, riippuen onnistuiko tiedoston siirto. Jos tiedoston haku epäonnistui, näytetään virheilmoitus:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Muussa tapauksessa jatketaan tiedoston avaamista.<br />
<br />
Luomme uuden QFile:n välittämällä sen muodostajaan <tt>NetAccess::download()</tt>:n luoman väliaikaistiedoston jonka jälkeen avataan se kirjoitussuojattuna:<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
Tuodaksemme avaamamme tiedoston sisällön ruudulle näkyviin, tarvitsee meidän käyttää {{class|QTextStream}}-luokkaa. {{class|QTextStream}}:n muodostajalle välitämme äsken avaamamme tiedoston (QFile file) ja kutsumme QFile:n <tt>readAll()</tt>-funktiota saadaksemme tekstin tiedostosta. Seuraavaksi välitämme tämän kaiken meidän tekstialueen <tt>setPlainText()</tt>-funktiolle:<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
Talletetaan avatun tiedoston nimi(polkuineen):<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
<br />
Ja lopuksi poistetaan <tt>NetAccess::download()</tt>:n luoma väliaikaistiedosto:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Käännä, Asenna ja Suorita==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
Koska otimme nyt KIO-kirjaston käyttöön, tarvitsee meidän kertoa CMakelle että linkittäjän tarvitsee ottaa myös tämä mukaan. Tätä varten lisäämme <tt>target_link_libraries()</tt>-funktioon tiedon <tt>${KDE4_KIO_LIBS}</tt>.<br />
<br />
=== Komennot ===<br />
Itse käännös, asennus ja suoritus menee samalla tavalla kuin Perehdytyksessä 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19820Development/Tutorials/Saving and loading (fi)2008-01-17T06:48:39Z<p>Ozzi: /* Loading a file */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> // *uusi*<br />
#include <KMessageBox> //*uusi*<br />
#include <KIO/NetAccess> //*uusi*<br />
#include <KSaveFile> //*uusi*<br />
#include <QTextStream> //*uusi*<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //*uusi*<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //*uusi*<br />
<br />
setupGUI();<br />
}<br />
<br />
// * uutta tästä eteenpäin *<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
Tämä on muuten identtinen <tt>tutorial3ui.rc</tt> kanssa, paitsi <tt>nimi</tt> on muutettu 'tutorial4':ksi. Koska kaikki uudet toiminnot ovat <tt>KStandardAction</tt>:ta jotka KDE osaa automaattisesti käsitellä, tähän tiedostoon ei tarvitse lisätä mitään.<br />
<br />
==Selvitys==<br />
<br />
Selvitetään nyt hieman koodia joka tekee avaamisen sekä ja tallettamisen. Kaikki tarvittava on sijoitettu <tt>mainwindow.cpp</tt>-tiedostoon.<br />
<br />
Ensimmäisenä, rivillä 16, meidän pitää lisätä<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
<tt>MainWindow</tt>:n muodostajaan. Tällä varmistetaan että tiedoston nimi on tyhjä aloitettaessa.<br />
<br />
===Toimintojen lisääminen===<br />
<br />
Ensinnäkin meidän pitää lisätä liittymä ohjelman ulkopuolelle, jotta käyttäjät voivat kertoa ohjelmalle avataanko vai talletetaanko tiedosto. Samaan tapaan kuin Perehdytyksessä 3, <tt>lopeta</tt>-toiminnon kanssa, käytämme tähänkin tarkoitukseen <tt>KStandardActions</tt>:a riveillä 37-47. Kaikki uudet toiminnot on kytketty sopiviin sloteihin jotka esittelimme otsikkotiedostossa riveillä 20-24. <br />
<br />
===Uusi asiakirja===<br />
<br />
Ensimmäisenä funktio jonka loimme on <tt>newFile()</tt>-funktio.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<tt>fileName.clear()</tt> asettaa <tt>fileName</tt> (QString) merkkijonon tyhjäksi kuvaamaan että tätä tiedostoa ei ole olemassa talletettuna minnekkään. <br />
<tt>textArea->clear()</tt> tyhjentää tekstialueen käyttäen samaa <tt>KAction</tt>:n <tt>clear</tt>-funktiota johon kytkimme Tyhjennä-toimionnon Perehdytyksessä 3.<br />
<br />
===Tiedoston tallettaminen===<br />
<br />
====saveFileAs(QString)====<br />
<br />
Siirrymme nyt ensimmäiseen tiedostoja käsittelevään koodiin. Seuraavaksi syvennymme funktioon jonka tehtävänä on tallentaa tekstialueen sisältö paramterinä annetulla tiedostonimellä. KDE tarjoaa turvalliseen tiedoston tallettamiseen Qt:n {{qt|QFile}}:a johdetun {{class|KSaveFile}}-luokan.<br />
<br />
Funktion prototyyppi on:<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
Seuraavaksi luomme <tt>KSaveFile</tt>-objektin ja avaamme sen<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
Nyt kun meillä on tiedosto johon kirjoittaa, meidän pitää muotoilla teksti alueen sisältö sellaiseen muotoon joka on mahdollista kirjoittaa tiedostoon. Tätä tarkoitusta varten luomme {{qt|QByteArray}}:n johon syötämme tekstialueen sisällön tekstinä, ilman muotoiluja, seuraavasti: <br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
Nyt meillä on <tt>KSaveFile::write()</tt>:n kanssa käytettävä <tt>QByteArray</tt> calmiina. Normaalin <tt>QFile</tt>:n käyttäminen olisi myös mahdollista, ja se tallettaisi muutokset välittömästi, mutta jos tällöin tapahtuisi jokin virhe tallentamisen aikana, tulisi tiedostosta viallinen. Tästä syystä <tt>KSaveFile</tt> luo ensin väliaikaisen tiedoston, ja vasta kun kutsutaan <tt>KSaveFile::finalize()</tt>-funktiota, luodaan varsinainen tiedosto.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Ja lopuksi asetetaan <tt>MainWindows</tt>:n <tt>fileName</tt> osoittamaan tiedostoon jonka juuri tallensimme:<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
Tähän funktioon on yhdistetty <tt>saveAs</tt>(Tallenna nimellä) toiminto. Tämä funktio kutsuu <tt>saveFileAs(QString)</tt>-funktiota jolle lähetetään parametrinä <br />
<tt>{{class|KFileDialog}}::[http://api.kde.org/4.0-api/kdelibs-apidocs/kio/html/classKFileDialog.html#8891356c249c5911e1ab15cc2739a89b getSaveFileName()]</tt>:n palauttama tiedoston nimi.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
Tässä kohdassa käytämme ensimmäisen kerran KIO-kirjastoa. {{class|KFileDialog}}-luokka tarjoaa meille joukon funktioita joita kaikki KDE ohjelmat käyttävät yleisten tiedostovalikoiden näyttämiseen. <tt>KFileDialog::getSaveFileName()</tt>-funktion kutsuminen tuo esille tiedostovalikon jossa käyttäjä voi valita tai vaihtaa tiedoston nimeä tai tallennussijaintia. Funktio palauttaa täydellisen tiedoston nimen, jonka me välitimme <tt>saveFileAs(QString)</tt>-funktiolle.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
Tässä funktiossa ei ole mitään erityistä tai uutta. Tässä vain päätellään, näytetäänkö tallennusvalikko vai ei. Jos <tt>fileName</tt> ei ole tyhjä, tallennetaan tiedosto mitään kysymättä nimellä joka on sijoitettuna <tt>fileName</tt>:n kutsumalla saveFileAs(QString)-funktiota, muuten kutsutaan yllä olevaa saveFileAs()-funktiota.<br />
<br />
===Tiedoston avaaminen===<br />
<br />
Lopulta olemme valmiit tarkastelemaan tiedoston avaamista levyltä. Kaikki koodi tätä tarkoitusta varten on sijoitettu <tt>MainWindow::openFile()</tt>-funktioon.<br />
<br />
Ensin meidän pitää kysyä käyttäjältä, mikä tiedosto halutaan avattavan. Tätä tarkoitusta varten me käytämme toista <tt>KFileDialog</tt>-funktiota, <tt>getOpenFileName()</tt>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
Seuraavaksi käytämme KIO-kirjastoa tiedoston avaamiseen. KIO-kirjasto antaa meille mahdollisuuden avata tiedosto QFilen avulla, paikalliselta levyltä tai etäkoneelta, vaikkapa FTP:n yli. Tiedoston avaamiseksi käytämme {{class|NetAccess}}:n <tt>download()</tt>-funktiota:<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
Ensimmäinen argumentti on avattavan tiedoston nimi. Toinen on QString, joka tiedoston hakemisen jälkeen, sisältää väliaikaisen tiedoston sijainnin. Tämän <tt>tmpFile</tt>:n kanssa jatkamme tästä eteenpäin.<br />
<br />
Funktio palauttaa boolen arvon <tt>tosi</tt> tai <tt>epätosi</tt>, riippuen onnistuiko tiedoston siirto. Jos tiedoston haku epäonnistui, näytetään virheilmoitus:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Muussa tapauksessa jatketaan tiedoston avaamista.<br />
<br />
Luomme uuden QFile:n välittämällä sen muodostajaan <tt>NetAccess::download()</tt>:n luoman väliaikaistiedoston jonka jälkeen avataan se kirjoitussuojattuna:<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
Tuodaksemme avaamamme tiedoston sisällön ruudulle näkyviin, tarvitsee meidän käyttää {{class|QTextStream}}-luokkaa. {{class|QTextStream}}:n muodostajalle välitämme äsken avaamamme tiedoston (QFile file) ja kutsumme QFile:n <tt>readAll()</tt>-funktiota saadaksemme tekstin tiedostosta. Seuraavaksi välitämme tämän kaiken meidän tekstialueen <tt>setPlainText()</tt>-funktiolle:<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
Talletetaan avatun tiedoston nimi(polkuineen):<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
<br />
Ja lopuksi poistetaan <tt>NetAccess::download()</tt>:n luoma väliaikaistiedosto:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19693Development/Tutorials/Saving and loading (fi)2008-01-14T09:29:17Z<p>Ozzi: /* saveFile() */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> // *uusi*<br />
#include <KMessageBox> //*uusi*<br />
#include <KIO/NetAccess> //*uusi*<br />
#include <KSaveFile> //*uusi*<br />
#include <QTextStream> //*uusi*<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //*uusi*<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //*uusi*<br />
<br />
setupGUI();<br />
}<br />
<br />
// * uutta tästä eteenpäin *<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
Tämä on muuten identtinen <tt>tutorial3ui.rc</tt> kanssa, paitsi <tt>nimi</tt> on muutettu 'tutorial4':ksi. Koska kaikki uudet toiminnot ovat <tt>KStandardAction</tt>:ta jotka KDE osaa automaattisesti käsitellä, tähän tiedostoon ei tarvitse lisätä mitään.<br />
<br />
==Selvitys==<br />
<br />
Selvitetään nyt hieman koodia joka tekee avaamisen sekä ja tallettamisen. Kaikki tarvittava on sijoitettu <tt>mainwindow.cpp</tt>-tiedostoon.<br />
<br />
Ensimmäisenä, rivillä 16, meidän pitää lisätä<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
<tt>MainWindow</tt>:n muodostajaan. Tällä varmistetaan että tiedoston nimi on tyhjä aloitettaessa.<br />
<br />
===Toimintojen lisääminen===<br />
<br />
Ensinnäkin meidän pitää lisätä liittymä ohjelman ulkopuolelle, jotta käyttäjät voivat kertoa ohjelmalle avataanko vai talletetaanko tiedosto. Samaan tapaan kuin Perehdytyksessä 3, <tt>lopeta</tt>-toiminnon kanssa, käytämme tähänkin tarkoitukseen <tt>KStandardActions</tt>:a riveillä 37-47. Kaikki uudet toiminnot on kytketty sopiviin sloteihin jotka esittelimme otsikkotiedostossa riveillä 20-24. <br />
<br />
===Uusi asiakirja===<br />
<br />
Ensimmäisenä funktio jonka loimme on <tt>newFile()</tt>-funktio.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<tt>fileName.clear()</tt> asettaa <tt>fileName</tt> (QString) merkkijonon tyhjäksi kuvaamaan että tätä tiedostoa ei ole olemassa talletettuna minnekkään. <br />
<tt>textArea->clear()</tt> tyhjentää tekstialueen käyttäen samaa <tt>KAction</tt>:n <tt>clear</tt>-funktiota johon kytkimme Tyhjennä-toimionnon Perehdytyksessä 3.<br />
<br />
===Tiedoston tallettaminen===<br />
<br />
====saveFileAs(QString)====<br />
<br />
Siirrymme nyt ensimmäiseen tiedostoja käsittelevään koodiin. Seuraavaksi syvennymme funktioon jonka tehtävänä on tallentaa tekstialueen sisältö paramterinä annetulla tiedostonimellä. KDE tarjoaa turvalliseen tiedoston tallettamiseen Qt:n {{qt|QFile}}:a johdetun {{class|KSaveFile}}-luokan.<br />
<br />
Funktion prototyyppi on:<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
Seuraavaksi luomme <tt>KSaveFile</tt>-objektin ja avaamme sen<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
Nyt kun meillä on tiedosto johon kirjoittaa, meidän pitää muotoilla teksti alueen sisältö sellaiseen muotoon joka on mahdollista kirjoittaa tiedostoon. Tätä tarkoitusta varten luomme {{qt|QByteArray}}:n johon syötämme tekstialueen sisällön tekstinä, ilman muotoiluja, seuraavasti: <br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
Nyt meillä on <tt>KSaveFile::write()</tt>:n kanssa käytettävä <tt>QByteArray</tt> calmiina. Normaalin <tt>QFile</tt>:n käyttäminen olisi myös mahdollista, ja se tallettaisi muutokset välittömästi, mutta jos tällöin tapahtuisi jokin virhe tallentamisen aikana, tulisi tiedostosta viallinen. Tästä syystä <tt>KSaveFile</tt> luo ensin väliaikaisen tiedoston, ja vasta kun kutsutaan <tt>KSaveFile::finalize()</tt>-funktiota, luodaan varsinainen tiedosto.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Ja lopuksi asetetaan <tt>MainWindows</tt>:n <tt>fileName</tt> osoittamaan tiedostoon jonka juuri tallensimme:<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
Tähän funktioon on yhdistetty <tt>saveAs</tt>(Tallenna nimellä) toiminto. Tämä funktio kutsuu <tt>saveFileAs(QString)</tt>-funktiota jolle lähetetään parametrinä <br />
<tt>{{class|KFileDialog}}::[http://api.kde.org/4.0-api/kdelibs-apidocs/kio/html/classKFileDialog.html#8891356c249c5911e1ab15cc2739a89b getSaveFileName()]</tt>:n palauttama tiedoston nimi.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
Tässä kohdassa käytämme ensimmäisen kerran KIO-kirjastoa. {{class|KFileDialog}}-luokka tarjoaa meille joukon funktioita joita kaikki KDE ohjelmat käyttävät yleisten tiedostovalikoiden näyttämiseen. <tt>KFileDialog::getSaveFileName()</tt>-funktion kutsuminen tuo esille tiedostovalikon jossa käyttäjä voi valita tai vaihtaa tiedoston nimeä tai tallennussijaintia. Funktio palauttaa täydellisen tiedoston nimen, jonka me välitimme <tt>saveFileAs(QString)</tt>-funktiolle.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
Tässä funktiossa ei ole mitään erityistä tai uutta. Tässä vain päätellään, näytetäänkö tallennusvalikko vai ei. Jos <tt>fileName</tt> ei ole tyhjä, tallennetaan tiedosto mitään kysymättä nimellä joka on sijoitettuna <tt>fileName</tt>:n kutsumalla saveFileAs(QString)-funktiota, muuten kutsutaan yllä olevaa saveFileAs()-funktiota.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19692Development/Tutorials/Saving and loading (fi)2008-01-14T09:23:15Z<p>Ozzi: /* saveFileAs() */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> // *uusi*<br />
#include <KMessageBox> //*uusi*<br />
#include <KIO/NetAccess> //*uusi*<br />
#include <KSaveFile> //*uusi*<br />
#include <QTextStream> //*uusi*<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //*uusi*<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //*uusi*<br />
<br />
setupGUI();<br />
}<br />
<br />
// * uutta tästä eteenpäin *<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
Tämä on muuten identtinen <tt>tutorial3ui.rc</tt> kanssa, paitsi <tt>nimi</tt> on muutettu 'tutorial4':ksi. Koska kaikki uudet toiminnot ovat <tt>KStandardAction</tt>:ta jotka KDE osaa automaattisesti käsitellä, tähän tiedostoon ei tarvitse lisätä mitään.<br />
<br />
==Selvitys==<br />
<br />
Selvitetään nyt hieman koodia joka tekee avaamisen sekä ja tallettamisen. Kaikki tarvittava on sijoitettu <tt>mainwindow.cpp</tt>-tiedostoon.<br />
<br />
Ensimmäisenä, rivillä 16, meidän pitää lisätä<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
<tt>MainWindow</tt>:n muodostajaan. Tällä varmistetaan että tiedoston nimi on tyhjä aloitettaessa.<br />
<br />
===Toimintojen lisääminen===<br />
<br />
Ensinnäkin meidän pitää lisätä liittymä ohjelman ulkopuolelle, jotta käyttäjät voivat kertoa ohjelmalle avataanko vai talletetaanko tiedosto. Samaan tapaan kuin Perehdytyksessä 3, <tt>lopeta</tt>-toiminnon kanssa, käytämme tähänkin tarkoitukseen <tt>KStandardActions</tt>:a riveillä 37-47. Kaikki uudet toiminnot on kytketty sopiviin sloteihin jotka esittelimme otsikkotiedostossa riveillä 20-24. <br />
<br />
===Uusi asiakirja===<br />
<br />
Ensimmäisenä funktio jonka loimme on <tt>newFile()</tt>-funktio.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<tt>fileName.clear()</tt> asettaa <tt>fileName</tt> (QString) merkkijonon tyhjäksi kuvaamaan että tätä tiedostoa ei ole olemassa talletettuna minnekkään. <br />
<tt>textArea->clear()</tt> tyhjentää tekstialueen käyttäen samaa <tt>KAction</tt>:n <tt>clear</tt>-funktiota johon kytkimme Tyhjennä-toimionnon Perehdytyksessä 3.<br />
<br />
===Tiedoston tallettaminen===<br />
<br />
====saveFileAs(QString)====<br />
<br />
Siirrymme nyt ensimmäiseen tiedostoja käsittelevään koodiin. Seuraavaksi syvennymme funktioon jonka tehtävänä on tallentaa tekstialueen sisältö paramterinä annetulla tiedostonimellä. KDE tarjoaa turvalliseen tiedoston tallettamiseen Qt:n {{qt|QFile}}:a johdetun {{class|KSaveFile}}-luokan.<br />
<br />
Funktion prototyyppi on:<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
Seuraavaksi luomme <tt>KSaveFile</tt>-objektin ja avaamme sen<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
Nyt kun meillä on tiedosto johon kirjoittaa, meidän pitää muotoilla teksti alueen sisältö sellaiseen muotoon joka on mahdollista kirjoittaa tiedostoon. Tätä tarkoitusta varten luomme {{qt|QByteArray}}:n johon syötämme tekstialueen sisällön tekstinä, ilman muotoiluja, seuraavasti: <br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
Nyt meillä on <tt>KSaveFile::write()</tt>:n kanssa käytettävä <tt>QByteArray</tt> calmiina. Normaalin <tt>QFile</tt>:n käyttäminen olisi myös mahdollista, ja se tallettaisi muutokset välittömästi, mutta jos tällöin tapahtuisi jokin virhe tallentamisen aikana, tulisi tiedostosta viallinen. Tästä syystä <tt>KSaveFile</tt> luo ensin väliaikaisen tiedoston, ja vasta kun kutsutaan <tt>KSaveFile::finalize()</tt>-funktiota, luodaan varsinainen tiedosto.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Ja lopuksi asetetaan <tt>MainWindows</tt>:n <tt>fileName</tt> osoittamaan tiedostoon jonka juuri tallensimme:<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
Tähän funktioon on yhdistetty <tt>saveAs</tt>(Tallenna nimellä) toiminto. Tämä funktio kutsuu <tt>saveFileAs(QString)</tt>-funktiota jolle lähetetään parametrinä <br />
<tt>{{class|KFileDialog}}::[http://api.kde.org/4.0-api/kdelibs-apidocs/kio/html/classKFileDialog.html#8891356c249c5911e1ab15cc2739a89b getSaveFileName()]</tt>:n palauttama tiedoston nimi.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
Tässä kohdassa käytämme ensimmäisen kerran KIO-kirjastoa. {{class|KFileDialog}}-luokka tarjoaa meille joukon funktioita joita kaikki KDE ohjelmat käyttävät yleisten tiedostovalikoiden näyttämiseen. <tt>KFileDialog::getSaveFileName()</tt>-funktion kutsuminen tuo esille tiedostovalikon jossa käyttäjä voi valita tai vaihtaa tiedoston nimeä tai tallennussijaintia. Funktio palauttaa täydellisen tiedoston nimen, jonka me välitimme <tt>saveFileAs(QString)</tt>-funktiolle.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19691Development/Tutorials/Saving and loading (fi)2008-01-14T09:12:36Z<p>Ozzi: /* Saving a file */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> // *uusi*<br />
#include <KMessageBox> //*uusi*<br />
#include <KIO/NetAccess> //*uusi*<br />
#include <KSaveFile> //*uusi*<br />
#include <QTextStream> //*uusi*<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //*uusi*<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //*uusi*<br />
<br />
setupGUI();<br />
}<br />
<br />
// * uutta tästä eteenpäin *<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
Tämä on muuten identtinen <tt>tutorial3ui.rc</tt> kanssa, paitsi <tt>nimi</tt> on muutettu 'tutorial4':ksi. Koska kaikki uudet toiminnot ovat <tt>KStandardAction</tt>:ta jotka KDE osaa automaattisesti käsitellä, tähän tiedostoon ei tarvitse lisätä mitään.<br />
<br />
==Selvitys==<br />
<br />
Selvitetään nyt hieman koodia joka tekee avaamisen sekä ja tallettamisen. Kaikki tarvittava on sijoitettu <tt>mainwindow.cpp</tt>-tiedostoon.<br />
<br />
Ensimmäisenä, rivillä 16, meidän pitää lisätä<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
<tt>MainWindow</tt>:n muodostajaan. Tällä varmistetaan että tiedoston nimi on tyhjä aloitettaessa.<br />
<br />
===Toimintojen lisääminen===<br />
<br />
Ensinnäkin meidän pitää lisätä liittymä ohjelman ulkopuolelle, jotta käyttäjät voivat kertoa ohjelmalle avataanko vai talletetaanko tiedosto. Samaan tapaan kuin Perehdytyksessä 3, <tt>lopeta</tt>-toiminnon kanssa, käytämme tähänkin tarkoitukseen <tt>KStandardActions</tt>:a riveillä 37-47. Kaikki uudet toiminnot on kytketty sopiviin sloteihin jotka esittelimme otsikkotiedostossa riveillä 20-24. <br />
<br />
===Uusi asiakirja===<br />
<br />
Ensimmäisenä funktio jonka loimme on <tt>newFile()</tt>-funktio.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<tt>fileName.clear()</tt> asettaa <tt>fileName</tt> (QString) merkkijonon tyhjäksi kuvaamaan että tätä tiedostoa ei ole olemassa talletettuna minnekkään. <br />
<tt>textArea->clear()</tt> tyhjentää tekstialueen käyttäen samaa <tt>KAction</tt>:n <tt>clear</tt>-funktiota johon kytkimme Tyhjennä-toimionnon Perehdytyksessä 3.<br />
<br />
===Tiedoston tallettaminen===<br />
<br />
====saveFileAs(QString)====<br />
<br />
Siirrymme nyt ensimmäiseen tiedostoja käsittelevään koodiin. Seuraavaksi syvennymme funktioon jonka tehtävänä on tallentaa tekstialueen sisältö paramterinä annetulla tiedostonimellä. KDE tarjoaa turvalliseen tiedoston tallettamiseen Qt:n {{qt|QFile}}:a johdetun {{class|KSaveFile}}-luokan.<br />
<br />
Funktion prototyyppi on:<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
Seuraavaksi luomme <tt>KSaveFile</tt>-objektin ja avaamme sen<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
Nyt kun meillä on tiedosto johon kirjoittaa, meidän pitää muotoilla teksti alueen sisältö sellaiseen muotoon joka on mahdollista kirjoittaa tiedostoon. Tätä tarkoitusta varten luomme {{qt|QByteArray}}:n johon syötämme tekstialueen sisällön tekstinä, ilman muotoiluja, seuraavasti: <br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
Nyt meillä on <tt>KSaveFile::write()</tt>:n kanssa käytettävä <tt>QByteArray</tt> calmiina. Normaalin <tt>QFile</tt>:n käyttäminen olisi myös mahdollista, ja se tallettaisi muutokset välittömästi, mutta jos tällöin tapahtuisi jokin virhe tallentamisen aikana, tulisi tiedostosta viallinen. Tästä syystä <tt>KSaveFile</tt> luo ensin väliaikaisen tiedoston, ja vasta kun kutsutaan <tt>KSaveFile::finalize()</tt>-funktiota, luodaan varsinainen tiedosto.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Ja lopuksi asetetaan <tt>MainWindows</tt>:n <tt>fileName</tt> osoittamaan tiedostoon jonka juuri tallensimme:<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19688Development/Tutorials/Saving and loading (fi)2008-01-14T08:16:46Z<p>Ozzi: /* Explanation */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> // *uusi*<br />
#include <KMessageBox> //*uusi*<br />
#include <KIO/NetAccess> //*uusi*<br />
#include <KSaveFile> //*uusi*<br />
#include <QTextStream> //*uusi*<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //*uusi*<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //*uusi*<br />
<br />
setupGUI();<br />
}<br />
<br />
// * uutta tästä eteenpäin *<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
Tämä on muuten identtinen <tt>tutorial3ui.rc</tt> kanssa, paitsi <tt>nimi</tt> on muutettu 'tutorial4':ksi. Koska kaikki uudet toiminnot ovat <tt>KStandardAction</tt>:ta jotka KDE osaa automaattisesti käsitellä, tähän tiedostoon ei tarvitse lisätä mitään.<br />
<br />
==Selvitys==<br />
<br />
Selvitetään nyt hieman koodia joka tekee avaamisen sekä ja tallettamisen. Kaikki tarvittava on sijoitettu <tt>mainwindow.cpp</tt>-tiedostoon.<br />
<br />
Ensimmäisenä, rivillä 16, meidän pitää lisätä<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
<tt>MainWindow</tt>:n muodostajaan. Tällä varmistetaan että tiedoston nimi on tyhjä aloitettaessa.<br />
<br />
===Toimintojen lisääminen===<br />
<br />
Ensinnäkin meidän pitää lisätä liittymä ohjelman ulkopuolelle, jotta käyttäjät voivat kertoa ohjelmalle avataanko vai talletetaanko tiedosto. Samaan tapaan kuin Perehdytyksessä 3, <tt>lopeta</tt>-toiminnon kanssa, käytämme tähänkin tarkoitukseen <tt>KStandardActions</tt>:a riveillä 37-47. Kaikki uudet toiminnot on kytketty sopiviin sloteihin jotka esittelimme otsikkotiedostossa riveillä 20-24. <br />
<br />
===Uusi asiakirja===<br />
<br />
Ensimmäisenä funktio jonka loimme on <tt>newFile()</tt>-funktio.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<tt>fileName.clear()</tt> asettaa <tt>fileName</tt> (QString) merkkijonon tyhjäksi kuvaamaan että tätä tiedostoa ei ole olemassa talletettuna minnekkään. <br />
<tt>textArea->clear()</tt> tyhjentää tekstialueen käyttäen samaa <tt>KAction</tt>:n <tt>clear</tt>-funktiota johon kytkimme Tyhjennä-toimionnon Perehdytyksessä 3.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19546Development/Tutorials/Saving and loading (fi)2008-01-11T12:08:43Z<p>Ozzi: /* tutorial4ui.rc */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> // *uusi*<br />
#include <KMessageBox> //*uusi*<br />
#include <KIO/NetAccess> //*uusi*<br />
#include <KSaveFile> //*uusi*<br />
#include <QTextStream> //*uusi*<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //*uusi*<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //*uusi*<br />
<br />
setupGUI();<br />
}<br />
<br />
// * uutta tästä eteenpäin *<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
Tämä on muuten identtinen <tt>tutorial3ui.rc</tt> kanssa, paitsi <tt>nimi</tt> on muutettu 'tutorial4':ksi. Koska kaikki uudet toiminnot ovat <tt>KStandardAction</tt>:ta jotka KDE osaa automaattisesti käsitellä, tähän tiedostoon ei tarvitse lisätä mitään.<br />
<br />
==Explanation==<br />
<br />
Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt><br />
<br />
The first thing we do is add<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
to the <tt>MainWindow</tt> constructor list on line 16. This makes sure that <tt>fileName</tt> is empty right from the beginning.<br />
<br />
===Adding the actions===<br />
<br />
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.<br />
<br />
===Creating a new document===<br />
<br />
The first function we create is the <tt>newFile()</tt> function.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<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.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19544Development/Tutorials/Saving and loading (fi)2008-01-11T11:31:56Z<p>Ozzi: /* mainwindow.cpp */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> // *uusi*<br />
#include <KMessageBox> //*uusi*<br />
#include <KIO/NetAccess> //*uusi*<br />
#include <KSaveFile> //*uusi*<br />
#include <QTextStream> //*uusi*<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //*uusi*<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //*uusi*<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //*uusi*<br />
<br />
setupGUI();<br />
}<br />
<br />
// * uutta tästä eteenpäin *<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
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.<br />
<br />
==Explanation==<br />
<br />
Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt><br />
<br />
The first thing we do is add<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
to the <tt>MainWindow</tt> constructor list on line 16. This makes sure that <tt>fileName</tt> is empty right from the beginning.<br />
<br />
===Adding the actions===<br />
<br />
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.<br />
<br />
===Creating a new document===<br />
<br />
The first function we create is the <tt>newFile()</tt> function.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<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.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19543Development/Tutorials/Saving and loading (fi)2008-01-11T11:30:15Z<p>Ozzi: /* mainwindow.h */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT // *uusi*<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; // tiedoston nimi *uusi*<br />
<br />
private slots: // *uusi*<br />
void newFile(); // uusi tiedosto *uusi*<br />
void openFile(); // avaa tiedosto *uusi* <br />
void saveFile(); // tallenna tiedosto *uusi*<br />
void saveFileAs(); // tallenna tiedosto nimellä *uusi*<br />
void saveFileAs(const QString &outputFileName); // *uusi*<br />
};<br />
<br />
#endif<br />
</code><br />
Tiedostojen avaus ja tallennus mahdollisuuden aikaansaamiseksi meidän tarvitsee lisätä funktiot jotka tekevät tarvittavat asiat. Koska näitä funktoita tullaan kutsumaan Qt:n [http://doc.trolltech.com/latest/signalsandslots.html signal/slot]-yhdistämismekanismin kautta, meidän tarvitsee määritellä nämä funktiot <tt>slot</tt>:ksi. Tämä on toteutettu rivillä 19. Koska käytämme <tt>slot</tt>:a tässä otsikkotiedostossa, meidän tarvitsee lisätä myös [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] makro.<br />
<br />
Haluamme myös pitää muistissa avaamamme tiedoston nimen, joten meidän tarvitsee esitellä myös <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> //new<br />
#include <KMessageBox> //new<br />
#include <KIO/NetAccess> //new<br />
#include <KSaveFile> //new<br />
#include <QTextStream> //new<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //new<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //new<br />
<br />
setupGUI();<br />
}<br />
<br />
//New from here on<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
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.<br />
<br />
==Explanation==<br />
<br />
Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt><br />
<br />
The first thing we do is add<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
to the <tt>MainWindow</tt> constructor list on line 16. This makes sure that <tt>fileName</tt> is empty right from the beginning.<br />
<br />
===Adding the actions===<br />
<br />
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.<br />
<br />
===Creating a new document===<br />
<br />
The first function we create is the <tt>newFile()</tt> function.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<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.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19540Development/Tutorials/Saving and loading (fi)2008-01-11T10:53:36Z<p>Ozzi: /* main.cpp */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole muutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT //new from tutorial3<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; //new<br />
<br />
private slots: //new<br />
void newFile(); //new<br />
void openFile(); //new<br />
void saveFile(); //new<br />
void saveFileAs(); //new<br />
void saveFileAs(const QString &outputFileName); //new<br />
};<br />
<br />
#endif<br />
</code><br />
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.trolltech.com/latest/signalsandslots.html signal/slot] mechanism we must specify that these functions are slots as we do on line 19. Since we are using slots in this header file, we must also add the [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] macro.<br />
<br />
We also want to keep track of the filename of the currently opened file so we declare a <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> //new<br />
#include <KMessageBox> //new<br />
#include <KIO/NetAccess> //new<br />
#include <KSaveFile> //new<br />
#include <QTextStream> //new<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //new<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //new<br />
<br />
setupGUI();<br />
}<br />
<br />
//New from here on<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
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.<br />
<br />
==Explanation==<br />
<br />
Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt><br />
<br />
The first thing we do is add<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
to the <tt>MainWindow</tt> constructor list on line 16. This makes sure that <tt>fileName</tt> is empty right from the beginning.<br />
<br />
===Adding the actions===<br />
<br />
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.<br />
<br />
===Creating a new document===<br />
<br />
The first function we create is the <tt>newFile()</tt> function.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<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.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19539Development/Tutorials/Saving and loading (fi)2008-01-11T10:49:52Z<p>Ozzi: /* The Code */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole uutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT //new from tutorial3<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; //new<br />
<br />
private slots: //new<br />
void newFile(); //new<br />
void openFile(); //new<br />
void saveFile(); //new<br />
void saveFileAs(); //new<br />
void saveFileAs(const QString &outputFileName); //new<br />
};<br />
<br />
#endif<br />
</code><br />
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.trolltech.com/latest/signalsandslots.html signal/slot] mechanism we must specify that these functions are slots as we do on line 19. Since we are using slots in this header file, we must also add the [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] macro.<br />
<br />
We also want to keep track of the filename of the currently opened file so we declare a <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> //new<br />
#include <KMessageBox> //new<br />
#include <KIO/NetAccess> //new<br />
#include <KSaveFile> //new<br />
#include <QTextStream> //new<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //new<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //new<br />
<br />
setupGUI();<br />
}<br />
<br />
//New from here on<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
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.<br />
<br />
==Explanation==<br />
<br />
Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt><br />
<br />
The first thing we do is add<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
to the <tt>MainWindow</tt> constructor list on line 16. This makes sure that <tt>fileName</tt> is empty right from the beginning.<br />
<br />
===Adding the actions===<br />
<br />
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.<br />
<br />
===Creating a new document===<br />
<br />
The first function we create is the <tt>newFile()</tt> function.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<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.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19538Development/Tutorials/Saving and loading (fi)2008-01-11T10:49:26Z<p>Ozzi: /* main.cpp */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== The Code ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt>-tiedostoa ei ole uutettu mitenkään paitsi kaikki ''tutorial 3'':t on vaihdettu ''tutorial 4'':ksi.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT //new from tutorial3<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; //new<br />
<br />
private slots: //new<br />
void newFile(); //new<br />
void openFile(); //new<br />
void saveFile(); //new<br />
void saveFileAs(); //new<br />
void saveFileAs(const QString &outputFileName); //new<br />
};<br />
<br />
#endif<br />
</code><br />
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.trolltech.com/latest/signalsandslots.html signal/slot] mechanism we must specify that these functions are slots as we do on line 19. Since we are using slots in this header file, we must also add the [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] macro.<br />
<br />
We also want to keep track of the filename of the currently opened file so we declare a <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> //new<br />
#include <KMessageBox> //new<br />
#include <KIO/NetAccess> //new<br />
#include <KSaveFile> //new<br />
#include <QTextStream> //new<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //new<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //new<br />
<br />
setupGUI();<br />
}<br />
<br />
//New from here on<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
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.<br />
<br />
==Explanation==<br />
<br />
Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt><br />
<br />
The first thing we do is add<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
to the <tt>MainWindow</tt> constructor list on line 16. This makes sure that <tt>fileName</tt> is empty right from the beginning.<br />
<br />
===Adding the actions===<br />
<br />
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.<br />
<br />
===Creating a new document===<br />
<br />
The first function we create is the <tt>newFile()</tt> function.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<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.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19537Development/Tutorials/Saving and loading (fi)2008-01-11T10:47:59Z<p>Ozzi: /* Lyhyesti */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Lyhyesti==<br />
<br />
Nyt kun meillä on perus tekstieditori, on aika tehdä siitä jollain tavalla hyödyllinen. Jokaisen tekstieditorilla pitäisi pystyä vähintäänkin tallettamaan tehdyt työt levylle sekä avata tekstitiedostoja käsittelyä varten.<br />
<br />
KDE tarjoaa joukon luokkia tiedostojen kanssa työskentelyä varten jotka helpottavat ohjelmistokehittäjän elämää. KIO-kirjasto mahdollistaa helpon tiedostojen käsittelyn verkkoprotokollien yli sekä se tarjoaa vakioidun tiedosto valikon tiedostojen avaamista ja tallettamista varten.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== The Code ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt> hasn't changed from tutorial 3 except to change any reference to tutorial 3 to tutorial 4.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT //new from tutorial3<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; //new<br />
<br />
private slots: //new<br />
void newFile(); //new<br />
void openFile(); //new<br />
void saveFile(); //new<br />
void saveFileAs(); //new<br />
void saveFileAs(const QString &outputFileName); //new<br />
};<br />
<br />
#endif<br />
</code><br />
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.trolltech.com/latest/signalsandslots.html signal/slot] mechanism we must specify that these functions are slots as we do on line 19. Since we are using slots in this header file, we must also add the [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] macro.<br />
<br />
We also want to keep track of the filename of the currently opened file so we declare a <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> //new<br />
#include <KMessageBox> //new<br />
#include <KIO/NetAccess> //new<br />
#include <KSaveFile> //new<br />
#include <QTextStream> //new<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //new<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //new<br />
<br />
setupGUI();<br />
}<br />
<br />
//New from here on<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
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.<br />
<br />
==Explanation==<br />
<br />
Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt><br />
<br />
The first thing we do is add<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
to the <tt>MainWindow</tt> constructor list on line 16. This makes sure that <tt>fileName</tt> is empty right from the beginning.<br />
<br />
===Adding the actions===<br />
<br />
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.<br />
<br />
===Creating a new document===<br />
<br />
The first function we create is the <tt>newFile()</tt> function.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<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.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials_(fi)&diff=19536Development/Tutorials (fi)2008-01-11T10:41:37Z<p>Ozzi: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials}}<br />
<br />
Täältä löytyvät ohjeet ovat nopein tapa saada selville, mitä KDE tekee ja kuinka se tekee. T&auml;ss&auml; on luettelo t&auml;ll&auml; hetkell&auml; k&auml;ytett&auml;vist&auml; opastusohjeista <b>KDE4:lle</b>. Materiaali KDE3:lle ja KDE2:lle löytyy t&auml;m&auml;n sivun lopussa.<br />
<br />
== Perehdytys KDE 4 ohjelmointiin ==<br />
Kiinnostaako sovellusten kehitt&auml;minen KDE 4:lle? T&auml;m&auml; ohjesarja on tarkoitettu KDE-ohjelmointia aloitteleville.<br />
;[[Development/Tutorials/First program (fi)|Hei maailma!]]<br />
:''Perehdytt&auml;minen KDE4-ohjelmoinnin alkeisiin''<br />
<br />
;[[Development/Tutorials/Using KXmlGuiWindow (fi)|Main-ikkunan luonti]]<br />
:''T&auml;m&auml; ohje opettaa t&auml;rkeimm&auml;n taikatempun: main-ikkunan tekemisen.''<br />
<br />
;[[Development/Tutorials/Using KActions (fi)|KActions ja XMLGUI]]<br />
:''Kuinka valikkoihin ja ty&ouml;kalupalkkeihin lis&auml;t&auml;&auml;n toimintoja.''<br />
<br />
;[[Development/Tutorials/Saving_and_loading (fi)|Tallettaminen ja Avaaminen]]<br />
:''Kuinka tallentaa tiedostot sekä kuinka avata ne.''<br />
<br />
== Perusteet ==<br />
;[[Development/Tutorials/KDE4 Porting Guide|Sovelluksen siirto]]<br />
:''Opaste sovellusten siirtoon Qt3/KDE3:sta Qt4/KDE4:een''<br />
<br />
;[[Development/Tutorials/CMake_(fi)|CMake-perehdytys]]<br />
:''Kuinka k&auml;ytt&auml;&auml; KDE4:n k&auml;ytt&auml;m&auml;&auml; CMake-rakentamisj&auml;rjestelm&auml;&auml;.''<br />
<br />
;[[Development/Tutorials/Common Programming Mistakes|Yleiset ohjelmointivirheet]]<br />
:''Tässä esitellään yleisiä virheitä, joita tehd&auml;&auml;n Qt- ja KDE-sovellusten kehitt&auml;misen aikana ja opastetaan välttämään ne..''<br />
<br />
;[[Development/Tutorials/Using Qt Designer_(fi)|K&auml;ytet&auml;&auml;n Qt Designer-ohjelmaa k&auml;ytt&ouml;liittymien luomiseen]]<br />
:''Kuinka UI-tiedostoja luodaan Qt Designer -ohjelmalla ja kuinka ne integroidaan KDE-ohjelmaan.''<br />
<br />
;[[Development/Tutorials/Command-Line Options_(fi)|K&auml;ytet&auml;&auml;n komentorivivalitsimia]]<br />
:''Komentoriviargumentit haetaan ja käsitellään helposti KDE:n komentoriviargumenttiluokilla.''<br />
<br />
== Testaus ja virheenj&auml;ljitys ==<br />
<br />
;[[Development/Tutorials/Debugging|Sovelluksesi virheenj&auml;ljitys]]<br />
:''Vihjeit&auml;, ty&ouml;kaluja ja tekniikoita sovellettavaksi virheiden jäljittämiseksi KDE-sovelluksesta''<br />
<br />
;[[Development/Tutorials/Unittests|Kirjoitetaan yksikk&ouml;testej&auml; Qt4:lle ja KDE4:lle QTestLib-ohjelmalla]] ([http://developer.kde.org/documentation/tutorials/writingunittests/writingunittests.html Alkuper&auml;inen linkki])<br />
:''[mailto:bradh@frogmouth.net Brad Hards]in opas, joka esittää kuinka kirjoittaa yksikk&ouml;testej&auml; k&auml;ytt&auml;en QTestLib-kehyst&auml;. Opas perustuu esimerkkeihin, ja sitä kehitetään yhä.''<br />
<br />
;[[Development/Tutorials/Code_Checking|Puoliautomaattinen tapa havaita koodivirheet]]<br />
:''Tekniikoita, joita k&auml;ytet&auml;&auml;n virheiden havaitsemiseen KDE-koodissa''<br />
<br />
== Konfiguraatiotietojen hallinta KConfig-ohjelmalla ==<br />
;[[Development/Tutorials/KConfig|KConfig-perehdytys]]<br />
:''Yleiskatsaus KConfig-luokista ja kuinka niit&auml; k&auml;ytet&auml;&auml;n sovelluskoodissasi''<br />
<br />
;[[Development/Tutorials/Using KConfig XT|KConfig XT-k&auml;ytt&ouml;]]<br />
:''Opastusohjelma siit&auml; kuinka k&auml;ytet&auml;n tehokkaasti KConfig XT-kehyst&auml;.''<br />
<br />
;[[Development/Tutorials/Updating KConfig Files|KConfig-tiedostojen p&auml;ivitys]]<br />
:''Opastus päivitysskriptin kirjoittamiseksi. Päivitysskripti pitää sovelluksesi asetustiedostot yhdenmukaisena jo olemassa olevien asetustiedostojen kanssa''<br />
<br />
== Palvelut: Sovellukset ja lis&auml;osat ==<br />
;[[Development/Tutorials/Services/Introduction|Services-palvelukehysperehdytys]]<br />
:''Yleiskuva Services-palvelukehyksest&auml; KDE:ssa ja mit&auml; se tarjoaa sovelluskehitt&auml;j&auml;lle. Kattaa j&auml;rjestelm&auml;konfiguraatiov&auml;limuistin (SyCoCa), l&auml;hdedatatiedostot ja mit&auml; indeksoituja tietoja voidaan k&auml;ytt&auml;&auml;.''<br />
<br />
;[[Development/Tutorials/Services/Traders|Services-palvelujen l&ouml;yt&auml;minen k&auml;ytt&auml;en Trader-kyselyj&auml;]]<br />
:''Kuinka l&ouml;yt&auml;&auml; palveluja, kuten lis&auml;osat tai mime-tyypit, jotka on indeksoitu SyCoCa:ssa k&auml;ytt&auml;en Trader-kyselysyntaksia''<br />
<br />
;[[Development/Tutorials/Services/Plugins|Luodaan ja ladataan lis&auml;osia k&auml;ytt&auml;en KService-palvelua]]<br />
:''Opi kuinka m&auml;&auml;ritell&auml; r&auml;&auml;t&auml;l&ouml;ityj&auml; lis&auml;osatyyppej&auml;, l&ouml;ydet&auml;&auml;n asennettuja lis&auml;osia (mukaan lukien kolmansien osapuolien lis&auml;osat) ja lataa ne helpolla tavalla ja siirett&auml;v&auml;ss&auml; muodossa KService-palvelua k&auml;ytt&auml;en.''<br />
<br />
== Lokalisointi ==<br />
;[[Development/Tutorials/Localization/Unicode|Unicode-perehdytys]]<br />
:''Perehdytys Unicode-merkist&ouml;&ouml;n sekä Unicode-datan käsittelyyn KDE-sovelluksissa.''<br />
<br />
; [[Development/Tutorials/Localization/i18n|Sovellusten kirjoittaminen lokalisointi mieless&auml;]]<br />
:''T&auml;m&auml; opas kertoo, mit&auml; lokalisointi on, miksi se on t&auml;rke&auml;&auml; ja kuinka taataan, ett&auml; sovelluksesi on valmis lokalisoitavaksi. V&auml;ltt&auml;m&auml;t&ouml;ntä luettavaa kaikille sovelluskehitt&auml;jille.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Mistakes|Yleisten lokalisoitinkuoppien v&auml;ltt&auml;minen]]<br />
:''Monet yleiset virheet est&auml;v&auml;t sovellusten oikean lokalisoinnin. Selvit&auml; t&auml;st&auml; oppaasta mit&auml; nämä virheet ovat, ja kuinka vältät ne.''<br />
<br />
; [[Development/Tutorials/Localization/Building KDE's l10n Module|KDE:n lokalisointimoduulin rakentaminen]]<br />
:''Tämän oppaan avulla opit rakentamaan ja asentamaan kielituen KDE:n lokalisointi(l10n)moduulista, mikä on hyv&auml; ajatus KDE-pääsovellusten kanssa työskennellessä. Tekem&auml;ll&auml; niin voit testata sovellustasi toisella kielell&auml; ja paikantaa ongelma-alueet.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Build Systems|Sis&auml;llyt&auml; i18n rakentamisj&auml;rjestelm&auml;&auml;n]]<br />
:''Kun sovelluksesi on vihdoin valmis lokalisoitavaksi, seuraava vaihe on taata, ett&auml; k&auml;&auml;nn&ouml;stiedostot rakennetaan automaattisesti ja pidet&auml;&auml;n ajan tasalla. T&auml;m&auml; ohje kattaa v&auml;ltt&auml;tt&ouml;m&auml;t CMakeFiles.txt-lis&auml;kset samoin kuin jakeluprosessin, jonka tuloksena ovat sovelluksesi sanomaluettelot.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Challenges|Yleiset i18n-haasteet ja -ratkaisut]]<br />
:''Tämä opas käsittelee yleisiä lokalisointiongelmia: käsikirjojen kääntämistä, vanhentuneiden .po-tiedostojen yhdistelemistä ja käsittelemistä, versiojäädytyksiä, muilla kielillä kuin englanti koodaamista, riippumattomien julkaisujen luomista, sekä sovellusten siirtämistä KDE-moduulien välillä.''<br />
<br />
; [[Development/Tutorials/Localization/i18n_Semantics|Semanttiset sanomamerkinn&auml;t]]<br />
:''Yhdenmukaisen esityksen takaamiseksi ja sanomien paremman merkityksen ymm&auml;rt&auml;miseksi sovelluksissa voidaan liitt&auml;&auml; sanomiin semanttinen merkint&auml; k&auml;ytt&auml;en KUIT-j&auml;rjestelm&auml;&auml;. T&auml;m&auml; opas esittää, kuinka t&auml;m&auml; j&auml;rjestelm&auml; toimii.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Krazy|Automatisoitu i18n-kooditarkistus]]<br />
:''Krazy-kooditarkistin etsii KDE:n koodia ja ilmoittaa yleisist&auml; i18n-erehdyksist&auml;.''<br />
<br />
== Dokumentaatio ==<br />
<br />
;[[Development/Tutorials/API_Documentation|API-dokumentaatio]]<br />
:''T&auml;m&auml; opas esittää, kuinka API dokumentoidaan oikein.''<br />
<br />
;[[Development/Tutorials/Man_Pages|Man-sivut]]<br />
:''Kirjoitetaan ja luodaan käsikirjasivuja.''<br />
<br />
== Sovellusautomaatio ja skriptaus ==<br />
<br />
=== D-Bus ===<br />
; [[Development/Tutorials/D-Bus/Introduction|D-Bus-perehdytys]]<br />
:''Suoraan etenev&auml; perehdytt&auml;minen ydinkonsepteista D-Bus:ssa sovelluskehitt&auml;j&auml;n n&auml;k&ouml;kulmasta, t&auml;m&auml; opastusohje kattaa sen mit&auml; D-Bus on ja kuinka sovelluksen voivat k&auml;ytt&auml;&auml; sit&auml;.''<br />
; [[Development/Tutorials/D-Bus/Accessing Interfaces|Haetaan D-Bus rajapintoja]]<br />
:''Vaiheittain etenev&auml; opas D-Bus-metodien kutsumisesta ja kytkeytymisest&auml; D-Bus-signaaleihin k&auml;ytt&auml;en QtDBus-v&auml;yl&auml;&auml;.''<br />
; [[Development/Tutorials/D-Bus/Intermediate_D-Bus|Intermediate D-Bus]]<br />
:''Tips to make use of QtDBus when faced with problematic real-world interfaces.''<br />
; [[Development/Tutorials/D-Bus/Creating Interfaces|Luodaan D-Bus-rajapintoja]]<br />
:''Learn how to expose functionality in your application by creating and using custom D-Bus interfaces. Covers generating the XML descriptions, instantiating interfaces at run time and setting up the build system with CMake.''<br />
; [[Development/Tutorials/D-Bus/Autostart Services|D-Bus-automaattik&auml;ynnistyspalvelut]]<br />
:''Turn your application into a D-Bus autostart service with this tutorial. This D-Bus feature, also known as "D-Bus service activation", will ensure that even when your application isn't running that D-Bus calls made to it will work by relying on the D-Bus daemon itself to start your app if and when needed.''<br />
; [[Development/Tutorials/Porting_to_D-Bus|Porting from DCOP to D-Bus]]<br />
: ''Port your applications from DCOP to D-Bus with this handy guide.''<br />
<br />
=== Konqueror ===<br />
; [[Development/Tutorials/Creating Konqueror Service Menus|Luodaan Konqueror-palveluvalikoita]]<br />
:''Tämä opastusohje näyttää, kuinka luoda mime-tyyppikohtaisia toimintoja Konquerorin asiayhteysvalikossa (tunnetaan myös nimellä "palveluvalikot").''<br />
<br />
=== Kross ===<br />
; [[Development/Tutorials/Kross/Introduction|Kross-perehdytys]]<br />
:''Perehdytys Kross-skriptauskehykseen.''<br />
<br />
; [[Development/Tutorials/Kross/Hello_World|Hei maailma!]]<br />
:''Ensimmäinen sovellus toimivalla kross-koodilla.''<br />
<br />
; [[Development/Tutorials/Kross/Connecting_Signals_and_slots_in_Kross|Yhdistetään signaaleja ja Slots Kross:ssa]]<br />
:''Yksinkertainen demo-ohjelma objektien signaalien kytkemistä skriptisloteilla''<br />
<br />
; [[Development/Tutorials/Kross/Scripts-as-Plugins|Skriptit Kross-lisäosina]]<br />
:''Tämä opastusohje tarjoaa vaiheittaisen esittelyn siitä, kuinka integroida skriptit KDE-sovelluksen lisäosiksi.''<br />
<br />
=== KOffice ===<br />
; [[Development/Tutorials/KOffice Overview|KOffice-yleiskuvaus]]<br />
:''Tämä dokumentti esittää erilaisten KOffice-liitännäisten yleiskuvauksen ja kertoo, mikä on kunkin käyttötarkoitus ja erityisvahvuus.'' Jos olet aloittelija KOffice-lisäosien kohdalla, kannattaa aloittaa tästä.<br />
<br />
; [[Development/Tutorials/Write a Flake Plugin|Luodaan KOffice Flake-lisäosia]]<br />
:''Tämä opas näyttää, kuinka Koffice-sovelluksiin rakennetaan lisäosia, joiden avulla voidaan ODF-dokumentteihin upottaa sisältöä Flaken avulla.''<br />
<br />
; [[Development/Tutorials/KWord Scripting|KWord-skriptaus]]<br />
:''Tämä opas opettaa kehittämään KWord-skriptejä Pythonilla, Rubylla tai JavaScriptillä käyttäen Krossia.''<br />
<br />
; [[Development/Tutorials/KSpread Scripting|KSpread-skriptaus]]<br />
:''Tämä opas opettaa kehittämään KSpread-skriptejä Pythonilla, Rubylla tai JavaScriptillä käyttäen Krossia.''<br />
<br />
; [[Development/Tutorials/Krita Scripting|Krita-skriptaus]]<br />
:''Tämä opas opettaa kehittämään Krita-skriptejä Pythonilla, Rubylla tai JavaScriptillä käyttäen Krossia.''<br />
<br />
=== SuperKaramba ===<br />
; [[Development/Tutorials/SuperKaramba|SuperKaramba-opastusohje]]<br />
:''Tämä opastusohje tarjoaa SuperKaramba-yleiskuvan, teematiedostot ja Python-, Ruby- ja JavaScript-skriptauksen.''<br />
<br />
== Haku ja metadata ==<br />
<br />
=== Strigi ===<br />
<br />
; [[Development/Tutorials/Writing file analyzers|Tiedostoanalysaattorien kirjoittaminen]]<br />
:''Tiedostoanalysaattorit poimivat dataa tiedostosta näytettäväksi tiedostovalintaikkunoissa ja tiedostonhallintaohjelmissa. Tällä tavalla kerättyä dataa käytetään myös etsintään tiedostoille. KDE4 sallii useiden analysaattoreiden käytön per tiedostotyyppi. Tämä opas esittää, kuinka voit kirjoittaa uusia analysaattoreita.''<br />
<br />
=== Nepomuk ===<br />
<br />
; [[Development/Tutorials/Metadata/KMetaData first steps|Nepomuk ensi vaiheet]]<br />
:''Nepomuk on KDE-kirjasto, joka tarjoaa helpon pääsyn metadataan [http://nepomuk-kde.semanticdesktop.org Nepomuk-KDE]-järjestelmässä. Opi kuinka saat sovelluksesi luomaan ja lukemaan metadataa käyttäen Nepomuk-järjestelmää.''<br />
<br />
== Laitteistotietoisuus (Solid) ==<br />
<br />
;[[Development/Tutorials/Solid_Tutorials|Solid-perehdytys]]<br />
:''Perehdytys Solid-laitteiston havaitsemis- ja vuorovaikutusjärjestelmän käyttöön KDE-sovelluksissa.''<br />
<br />
;[[Development/Tutorials/Solid_Network_Tutorial|Tietoverkkotietojen haku]]<br />
:''Kuinka Solid-järjestelmää käytetään tietoverkkotietojen hakemiseen''<br />
<br />
== Multimedia (Phonon) ==<br />
<br />
;[[Development/Tutorials/Phonon/Introduction|Phonon]]<br />
:''Kuinka käynnistetään multimedia-API:lla''<br />
<br />
== Plasma ==<br />
<br />
;[[Development/Tutorials/Plasma/GettingStarted|Kuinka aloitetaan Plasmoidit]]<br />
:''Luo ensimmäinen Plasma-käyttöliittymäkomponenttisi tai Plasmoid, C++:ssa SVG-taustalla, kuvakkeella ja jollain tekstillä.''<br />
<br />
;[[Development/Tutorials/Plasma/DataEngines|Kirjoitetaan DataEngine-rajapinta]]<br />
:''DataEngine-rajapinnat tarjoavat vakioidun rajapinnan eri data-lähteisiin käytettäväksi visualisoinneille. Opi mitä DataEngine-rajapinta on ja kuinka oma rajapinta kirjoitetaan.''<br />
<br />
;[[Development/Tutorials/Plasma/UsingDataEngines|Käytetään DataEngine-rajapintoja Plasmoideissa]]<br />
:''DataEngine-rajapinnalla on mahdollista hakea dataa näytölle yksinkertaisella ja vakioidulla tavalla. Tämä opastusohje kattaa aiheen, kuinka DataEngine-rajapintoja käytetään tähän tarkoitukseen Plasmoideissa.''<br />
<br />
;[[Development/Tutorials/Plasma/AbstractRunner|Luodaan Runners-lisäosia]]<br />
:''Runners-lisäosat tarjoavat toimintaperustaisen hakutoiminnon Plasma-työtilan "suorita komento"-valintaikkunassa. Mikä tahansa sovellus, joka linkitetään libplasma-kirjastoon, voi käyttää näitä lisäosia.''<br />
<br />
== Kate / Kwrite ==<br />
<br />
;[[Development/Tutorials/Kate/KTextEditor Plugins|Kuinka aloitetaan KTextEditor-lis&auml;osakehitys]]<br />
:''Luo ensimm&auml;inen KTextEditor-lis&auml;osasi''<br />
<br />
==Tulostus==<br />
<br />
;[[Development/Tutorials/Printing Hello World|Hei maailma!]]<br />
:''Perehdytys KDE-tulostusj&auml;rjestelm&auml;&auml;n''<br />
<br />
;[[Development/Tutorials/Printing Print Dialog|Tulostusviestiruutu]]<br />
:''Kuinka k&auml;ytet&auml;&auml;n KDE-tulostusviestiruutua''<br />
<br />
== Hae uutta kuumaa kamaa ==<br />
; [[Development/Tutorials/Introduction to Get Hot New Stuff|Johdatus uuden kuuman matskun hakemiseen]]<br />
:''Johdatus käyttäjäystävälliseen tietoverkkopäivitysjärjestelmään, joka sallii KDE-sovellusten noutaa uutta sovellusdataa ajoaikaisesti käyttäjäystävällisellä tavalla.''<br />
<br />
;[[Development/Tutorials/KNewStuffSecure|Suojattu KNewStuff-verkko]] ([http://developer.kde.org/documentation/tutorials/knewstuffsecure/index.html Alkuperäinen linkki])<br />
:''Opastusohje näyttää, kuinka jakaa resursseja suojatulla tavalla (KDE 3.4 ja myöhemmät versiot).'' Laatija Andr&#225;s Mantia &lt;amantia@kde.org&gt;.<br />
<br />
== Nopea sovelluskehitys ==<br />
<br />
=== Python ===<br />
<br />
;[[Development/Tutorials/Python introduction to signals and slots|101 Johdatus signaaleihin ja väleihin]]<br />
:''Yksinkertainen johdatus Qt-signaali- ja väliarkkitehtuuriin.''<br />
<br />
=== Ruby ===<br />
<br />
;[http://developer.kde.org/language-bindings/ruby/kde3tutorial/index.html KDE Ruby Korundum opastusohje]<br />
:''Antonio Larrosa Jim&eacute;nez:n kirjoittama Ruby-versio Richard Dalen kirjoittamasta KDE-perehdytyksest&auml;. Katso [http://developer.kde.org/language-bindings/ruby/index.html Ruby-kehitt&auml;jien nurkkaus] Qt-opastusohjeille ja muille tiedoille.''<br />
<br />
;[[Development/Tutorials/Qt4_Ruby_Tutorial|Qt4 Ruby-opas]]<br />
:''Trolltech:n kuuluisa alustava Qt-opas muunnettuna Ruby-perehdytykseksi.''<br />
<br />
=== Komentotulkki ===<br />
<br />
;[[Development/Tutorials/Shell_Scripting_with_KDE_Dialogs|KDE-valintaikkunoita käyttävät komentotulkkiskriptit]] ([http://developer.kde.org/documentation/tutorials/kdialog/t1.html Alkuperäinen linkki]) <br />
:''[mailto:bradh@frogmouth.net Brad Hards]:in kirjoittama opas,joka kuvailee kuinka KDE-valintaikkunoita käytetään komentotulkkikripteissä kdialogin avulla.''<br />
<br />
== Muita opastusohjeita ==<br />
<br />
=== KDE Games-kirjaston k&auml;ytt&ouml; ===<br />
;[[Development/Tutorials/Games/KStandardGameAction| KStandardGameAction]]<br />
:''Käytetään libkdegames-kirjastoa, jotta pelisi sopisi kdegames-standardiin''<br />
;[[Development/Tutorials/Games/Highscores| Parhaat pisteet]]<br />
:''Toteutetaan yksinkertainen "parhaat pisteet"-taulukko peliisi''<br />
;[[Development/Tutorials/Games/Theme Selector| Teemavalitsin]]<br />
:''Käytetään libkdegames-kirjaston teemavalitsin valintaikkunaa''<br />
<br />
=== 2D-tulostus (KPlotWidget) ===<br />
;[[Development/Tutorials/KPlotWidget|Using the KDE data-plotting widget]]<br />
:''This tutorial introduces KPlotWidget, which is used for 2-D data plotting. It includes information on simple usage of the widget (including adding and modifying data sets, and customizing the plot axes and labels), and advanced customization (including extending the widget through sub-classing).''<br />
<br />
=== Oikeinkirjoitus- ja kielioppitarkistus (Sonnet) ===<br />
;[[Development/Tutorials/Sonnet/SonnetTutorial|Oikeinkirjoitus- ja kielioppitarkistuksen lis&auml;&auml;minen KDE-sovelluksiin]]<br />
:''T&auml;m&auml; opastusohje esittelee Sonnet-ohjelman ja sen käytön KDE-sovelluksesi kielen korjaamiseen. Sonnet-ohjelman lis&auml;ominaisuudet kuvaillaan erillisess&auml; oppaassa.''<br />
<br />
=== Pixmap-v&auml;limuisti (KPixmapCache) ===<br />
;[[Development/Tutorials/KPixmapCache|KDE pixmap-v&auml;limuistin k&auml;ytt&ouml;]]<br />
:''T&auml;m&auml; opastusohje n&auml;ytt&auml;&auml; kuinka KPixmapCache:lla sijoitetaan SVG-yksikk&ouml;jen ja muun datan luomia pixmap-kuvia KDE-v&auml;limuistiin.''<br />
<br />
== KDE2- ja KDE3-materiaalit ==<br />
<br />
;[[Development/Tutorials/KDE3|KDE3-opastusohjeet]]<br />
:''N&auml;m&auml; ohjeet kattavat KDE3-aiheet.''<br />
<br />
;[[Development/Tutorials/KDE2|KDE2-opastusohjeet]]<br />
:''N&auml;m&auml; ohjeet kattavat KDE2-aiheet''<br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials_(fi)&diff=19535Development/Tutorials (fi)2008-01-11T10:40:52Z<p>Ozzi: Lisätty linkki perehdytys 4:n</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials}}<br />
<br />
Täältä löytyvät ohjeet ovat nopein tapa saada selville, mitä KDE tekee ja kuinka se tekee. T&auml;ss&auml; on luettelo t&auml;ll&auml; hetkell&auml; k&auml;ytett&auml;vist&auml; opastusohjeista <b>KDE4:lle</b>. Materiaali KDE3:lle ja KDE2:lle löytyy t&auml;m&auml;n sivun lopussa.<br />
<br />
== Perehdytys KDE 4 ohjelmointiin ==<br />
Kiinnostaako sovellusten kehitt&auml;minen KDE 4:lle? T&auml;m&auml; ohjesarja on tarkoitettu KDE-ohjelmointia aloitteleville.<br />
;[[Development/Tutorials/First program (fi)|Hei maailma!]]<br />
:''Perehdytt&auml;minen KDE4-ohjelmoinnin alkeisiin''<br />
<br />
;[[Development/Tutorials/Using KXmlGuiWindow (fi)|Main-ikkunan luonti]]<br />
:''T&auml;m&auml; ohje opettaa t&auml;rkeimm&auml;n taikatempun: main-ikkunan tekemisen.''<br />
<br />
;[[Development/Tutorials/Using KActions (fi)|KActions ja XMLGUI]]<br />
:''Kuinka valikkoihin ja ty&ouml;kalupalkkeihin lis&auml;t&auml;&auml;n toimintoja.''<br />
<br />
;[[Development/Tutorials/Saving_and_loading (fi)|Tallettaminen ja Avaaminen]]<br />
;''Kuinka tallentaa tiedostot sekä kuinka avata ne.''<br />
<br />
== Perusteet ==<br />
;[[Development/Tutorials/KDE4 Porting Guide|Sovelluksen siirto]]<br />
:''Opaste sovellusten siirtoon Qt3/KDE3:sta Qt4/KDE4:een''<br />
<br />
;[[Development/Tutorials/CMake_(fi)|CMake-perehdytys]]<br />
:''Kuinka k&auml;ytt&auml;&auml; KDE4:n k&auml;ytt&auml;m&auml;&auml; CMake-rakentamisj&auml;rjestelm&auml;&auml;.''<br />
<br />
;[[Development/Tutorials/Common Programming Mistakes|Yleiset ohjelmointivirheet]]<br />
:''Tässä esitellään yleisiä virheitä, joita tehd&auml;&auml;n Qt- ja KDE-sovellusten kehitt&auml;misen aikana ja opastetaan välttämään ne..''<br />
<br />
;[[Development/Tutorials/Using Qt Designer_(fi)|K&auml;ytet&auml;&auml;n Qt Designer-ohjelmaa k&auml;ytt&ouml;liittymien luomiseen]]<br />
:''Kuinka UI-tiedostoja luodaan Qt Designer -ohjelmalla ja kuinka ne integroidaan KDE-ohjelmaan.''<br />
<br />
;[[Development/Tutorials/Command-Line Options_(fi)|K&auml;ytet&auml;&auml;n komentorivivalitsimia]]<br />
:''Komentoriviargumentit haetaan ja käsitellään helposti KDE:n komentoriviargumenttiluokilla.''<br />
<br />
== Testaus ja virheenj&auml;ljitys ==<br />
<br />
;[[Development/Tutorials/Debugging|Sovelluksesi virheenj&auml;ljitys]]<br />
:''Vihjeit&auml;, ty&ouml;kaluja ja tekniikoita sovellettavaksi virheiden jäljittämiseksi KDE-sovelluksesta''<br />
<br />
;[[Development/Tutorials/Unittests|Kirjoitetaan yksikk&ouml;testej&auml; Qt4:lle ja KDE4:lle QTestLib-ohjelmalla]] ([http://developer.kde.org/documentation/tutorials/writingunittests/writingunittests.html Alkuper&auml;inen linkki])<br />
:''[mailto:bradh@frogmouth.net Brad Hards]in opas, joka esittää kuinka kirjoittaa yksikk&ouml;testej&auml; k&auml;ytt&auml;en QTestLib-kehyst&auml;. Opas perustuu esimerkkeihin, ja sitä kehitetään yhä.''<br />
<br />
;[[Development/Tutorials/Code_Checking|Puoliautomaattinen tapa havaita koodivirheet]]<br />
:''Tekniikoita, joita k&auml;ytet&auml;&auml;n virheiden havaitsemiseen KDE-koodissa''<br />
<br />
== Konfiguraatiotietojen hallinta KConfig-ohjelmalla ==<br />
;[[Development/Tutorials/KConfig|KConfig-perehdytys]]<br />
:''Yleiskatsaus KConfig-luokista ja kuinka niit&auml; k&auml;ytet&auml;&auml;n sovelluskoodissasi''<br />
<br />
;[[Development/Tutorials/Using KConfig XT|KConfig XT-k&auml;ytt&ouml;]]<br />
:''Opastusohjelma siit&auml; kuinka k&auml;ytet&auml;n tehokkaasti KConfig XT-kehyst&auml;.''<br />
<br />
;[[Development/Tutorials/Updating KConfig Files|KConfig-tiedostojen p&auml;ivitys]]<br />
:''Opastus päivitysskriptin kirjoittamiseksi. Päivitysskripti pitää sovelluksesi asetustiedostot yhdenmukaisena jo olemassa olevien asetustiedostojen kanssa''<br />
<br />
== Palvelut: Sovellukset ja lis&auml;osat ==<br />
;[[Development/Tutorials/Services/Introduction|Services-palvelukehysperehdytys]]<br />
:''Yleiskuva Services-palvelukehyksest&auml; KDE:ssa ja mit&auml; se tarjoaa sovelluskehitt&auml;j&auml;lle. Kattaa j&auml;rjestelm&auml;konfiguraatiov&auml;limuistin (SyCoCa), l&auml;hdedatatiedostot ja mit&auml; indeksoituja tietoja voidaan k&auml;ytt&auml;&auml;.''<br />
<br />
;[[Development/Tutorials/Services/Traders|Services-palvelujen l&ouml;yt&auml;minen k&auml;ytt&auml;en Trader-kyselyj&auml;]]<br />
:''Kuinka l&ouml;yt&auml;&auml; palveluja, kuten lis&auml;osat tai mime-tyypit, jotka on indeksoitu SyCoCa:ssa k&auml;ytt&auml;en Trader-kyselysyntaksia''<br />
<br />
;[[Development/Tutorials/Services/Plugins|Luodaan ja ladataan lis&auml;osia k&auml;ytt&auml;en KService-palvelua]]<br />
:''Opi kuinka m&auml;&auml;ritell&auml; r&auml;&auml;t&auml;l&ouml;ityj&auml; lis&auml;osatyyppej&auml;, l&ouml;ydet&auml;&auml;n asennettuja lis&auml;osia (mukaan lukien kolmansien osapuolien lis&auml;osat) ja lataa ne helpolla tavalla ja siirett&auml;v&auml;ss&auml; muodossa KService-palvelua k&auml;ytt&auml;en.''<br />
<br />
== Lokalisointi ==<br />
;[[Development/Tutorials/Localization/Unicode|Unicode-perehdytys]]<br />
:''Perehdytys Unicode-merkist&ouml;&ouml;n sekä Unicode-datan käsittelyyn KDE-sovelluksissa.''<br />
<br />
; [[Development/Tutorials/Localization/i18n|Sovellusten kirjoittaminen lokalisointi mieless&auml;]]<br />
:''T&auml;m&auml; opas kertoo, mit&auml; lokalisointi on, miksi se on t&auml;rke&auml;&auml; ja kuinka taataan, ett&auml; sovelluksesi on valmis lokalisoitavaksi. V&auml;ltt&auml;m&auml;t&ouml;ntä luettavaa kaikille sovelluskehitt&auml;jille.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Mistakes|Yleisten lokalisoitinkuoppien v&auml;ltt&auml;minen]]<br />
:''Monet yleiset virheet est&auml;v&auml;t sovellusten oikean lokalisoinnin. Selvit&auml; t&auml;st&auml; oppaasta mit&auml; nämä virheet ovat, ja kuinka vältät ne.''<br />
<br />
; [[Development/Tutorials/Localization/Building KDE's l10n Module|KDE:n lokalisointimoduulin rakentaminen]]<br />
:''Tämän oppaan avulla opit rakentamaan ja asentamaan kielituen KDE:n lokalisointi(l10n)moduulista, mikä on hyv&auml; ajatus KDE-pääsovellusten kanssa työskennellessä. Tekem&auml;ll&auml; niin voit testata sovellustasi toisella kielell&auml; ja paikantaa ongelma-alueet.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Build Systems|Sis&auml;llyt&auml; i18n rakentamisj&auml;rjestelm&auml;&auml;n]]<br />
:''Kun sovelluksesi on vihdoin valmis lokalisoitavaksi, seuraava vaihe on taata, ett&auml; k&auml;&auml;nn&ouml;stiedostot rakennetaan automaattisesti ja pidet&auml;&auml;n ajan tasalla. T&auml;m&auml; ohje kattaa v&auml;ltt&auml;tt&ouml;m&auml;t CMakeFiles.txt-lis&auml;kset samoin kuin jakeluprosessin, jonka tuloksena ovat sovelluksesi sanomaluettelot.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Challenges|Yleiset i18n-haasteet ja -ratkaisut]]<br />
:''Tämä opas käsittelee yleisiä lokalisointiongelmia: käsikirjojen kääntämistä, vanhentuneiden .po-tiedostojen yhdistelemistä ja käsittelemistä, versiojäädytyksiä, muilla kielillä kuin englanti koodaamista, riippumattomien julkaisujen luomista, sekä sovellusten siirtämistä KDE-moduulien välillä.''<br />
<br />
; [[Development/Tutorials/Localization/i18n_Semantics|Semanttiset sanomamerkinn&auml;t]]<br />
:''Yhdenmukaisen esityksen takaamiseksi ja sanomien paremman merkityksen ymm&auml;rt&auml;miseksi sovelluksissa voidaan liitt&auml;&auml; sanomiin semanttinen merkint&auml; k&auml;ytt&auml;en KUIT-j&auml;rjestelm&auml;&auml;. T&auml;m&auml; opas esittää, kuinka t&auml;m&auml; j&auml;rjestelm&auml; toimii.''<br />
<br />
; [[Development/Tutorials/Localization/i18n Krazy|Automatisoitu i18n-kooditarkistus]]<br />
:''Krazy-kooditarkistin etsii KDE:n koodia ja ilmoittaa yleisist&auml; i18n-erehdyksist&auml;.''<br />
<br />
== Dokumentaatio ==<br />
<br />
;[[Development/Tutorials/API_Documentation|API-dokumentaatio]]<br />
:''T&auml;m&auml; opas esittää, kuinka API dokumentoidaan oikein.''<br />
<br />
;[[Development/Tutorials/Man_Pages|Man-sivut]]<br />
:''Kirjoitetaan ja luodaan käsikirjasivuja.''<br />
<br />
== Sovellusautomaatio ja skriptaus ==<br />
<br />
=== D-Bus ===<br />
; [[Development/Tutorials/D-Bus/Introduction|D-Bus-perehdytys]]<br />
:''Suoraan etenev&auml; perehdytt&auml;minen ydinkonsepteista D-Bus:ssa sovelluskehitt&auml;j&auml;n n&auml;k&ouml;kulmasta, t&auml;m&auml; opastusohje kattaa sen mit&auml; D-Bus on ja kuinka sovelluksen voivat k&auml;ytt&auml;&auml; sit&auml;.''<br />
; [[Development/Tutorials/D-Bus/Accessing Interfaces|Haetaan D-Bus rajapintoja]]<br />
:''Vaiheittain etenev&auml; opas D-Bus-metodien kutsumisesta ja kytkeytymisest&auml; D-Bus-signaaleihin k&auml;ytt&auml;en QtDBus-v&auml;yl&auml;&auml;.''<br />
; [[Development/Tutorials/D-Bus/Intermediate_D-Bus|Intermediate D-Bus]]<br />
:''Tips to make use of QtDBus when faced with problematic real-world interfaces.''<br />
; [[Development/Tutorials/D-Bus/Creating Interfaces|Luodaan D-Bus-rajapintoja]]<br />
:''Learn how to expose functionality in your application by creating and using custom D-Bus interfaces. Covers generating the XML descriptions, instantiating interfaces at run time and setting up the build system with CMake.''<br />
; [[Development/Tutorials/D-Bus/Autostart Services|D-Bus-automaattik&auml;ynnistyspalvelut]]<br />
:''Turn your application into a D-Bus autostart service with this tutorial. This D-Bus feature, also known as "D-Bus service activation", will ensure that even when your application isn't running that D-Bus calls made to it will work by relying on the D-Bus daemon itself to start your app if and when needed.''<br />
; [[Development/Tutorials/Porting_to_D-Bus|Porting from DCOP to D-Bus]]<br />
: ''Port your applications from DCOP to D-Bus with this handy guide.''<br />
<br />
=== Konqueror ===<br />
; [[Development/Tutorials/Creating Konqueror Service Menus|Luodaan Konqueror-palveluvalikoita]]<br />
:''Tämä opastusohje näyttää, kuinka luoda mime-tyyppikohtaisia toimintoja Konquerorin asiayhteysvalikossa (tunnetaan myös nimellä "palveluvalikot").''<br />
<br />
=== Kross ===<br />
; [[Development/Tutorials/Kross/Introduction|Kross-perehdytys]]<br />
:''Perehdytys Kross-skriptauskehykseen.''<br />
<br />
; [[Development/Tutorials/Kross/Hello_World|Hei maailma!]]<br />
:''Ensimmäinen sovellus toimivalla kross-koodilla.''<br />
<br />
; [[Development/Tutorials/Kross/Connecting_Signals_and_slots_in_Kross|Yhdistetään signaaleja ja Slots Kross:ssa]]<br />
:''Yksinkertainen demo-ohjelma objektien signaalien kytkemistä skriptisloteilla''<br />
<br />
; [[Development/Tutorials/Kross/Scripts-as-Plugins|Skriptit Kross-lisäosina]]<br />
:''Tämä opastusohje tarjoaa vaiheittaisen esittelyn siitä, kuinka integroida skriptit KDE-sovelluksen lisäosiksi.''<br />
<br />
=== KOffice ===<br />
; [[Development/Tutorials/KOffice Overview|KOffice-yleiskuvaus]]<br />
:''Tämä dokumentti esittää erilaisten KOffice-liitännäisten yleiskuvauksen ja kertoo, mikä on kunkin käyttötarkoitus ja erityisvahvuus.'' Jos olet aloittelija KOffice-lisäosien kohdalla, kannattaa aloittaa tästä.<br />
<br />
; [[Development/Tutorials/Write a Flake Plugin|Luodaan KOffice Flake-lisäosia]]<br />
:''Tämä opas näyttää, kuinka Koffice-sovelluksiin rakennetaan lisäosia, joiden avulla voidaan ODF-dokumentteihin upottaa sisältöä Flaken avulla.''<br />
<br />
; [[Development/Tutorials/KWord Scripting|KWord-skriptaus]]<br />
:''Tämä opas opettaa kehittämään KWord-skriptejä Pythonilla, Rubylla tai JavaScriptillä käyttäen Krossia.''<br />
<br />
; [[Development/Tutorials/KSpread Scripting|KSpread-skriptaus]]<br />
:''Tämä opas opettaa kehittämään KSpread-skriptejä Pythonilla, Rubylla tai JavaScriptillä käyttäen Krossia.''<br />
<br />
; [[Development/Tutorials/Krita Scripting|Krita-skriptaus]]<br />
:''Tämä opas opettaa kehittämään Krita-skriptejä Pythonilla, Rubylla tai JavaScriptillä käyttäen Krossia.''<br />
<br />
=== SuperKaramba ===<br />
; [[Development/Tutorials/SuperKaramba|SuperKaramba-opastusohje]]<br />
:''Tämä opastusohje tarjoaa SuperKaramba-yleiskuvan, teematiedostot ja Python-, Ruby- ja JavaScript-skriptauksen.''<br />
<br />
== Haku ja metadata ==<br />
<br />
=== Strigi ===<br />
<br />
; [[Development/Tutorials/Writing file analyzers|Tiedostoanalysaattorien kirjoittaminen]]<br />
:''Tiedostoanalysaattorit poimivat dataa tiedostosta näytettäväksi tiedostovalintaikkunoissa ja tiedostonhallintaohjelmissa. Tällä tavalla kerättyä dataa käytetään myös etsintään tiedostoille. KDE4 sallii useiden analysaattoreiden käytön per tiedostotyyppi. Tämä opas esittää, kuinka voit kirjoittaa uusia analysaattoreita.''<br />
<br />
=== Nepomuk ===<br />
<br />
; [[Development/Tutorials/Metadata/KMetaData first steps|Nepomuk ensi vaiheet]]<br />
:''Nepomuk on KDE-kirjasto, joka tarjoaa helpon pääsyn metadataan [http://nepomuk-kde.semanticdesktop.org Nepomuk-KDE]-järjestelmässä. Opi kuinka saat sovelluksesi luomaan ja lukemaan metadataa käyttäen Nepomuk-järjestelmää.''<br />
<br />
== Laitteistotietoisuus (Solid) ==<br />
<br />
;[[Development/Tutorials/Solid_Tutorials|Solid-perehdytys]]<br />
:''Perehdytys Solid-laitteiston havaitsemis- ja vuorovaikutusjärjestelmän käyttöön KDE-sovelluksissa.''<br />
<br />
;[[Development/Tutorials/Solid_Network_Tutorial|Tietoverkkotietojen haku]]<br />
:''Kuinka Solid-järjestelmää käytetään tietoverkkotietojen hakemiseen''<br />
<br />
== Multimedia (Phonon) ==<br />
<br />
;[[Development/Tutorials/Phonon/Introduction|Phonon]]<br />
:''Kuinka käynnistetään multimedia-API:lla''<br />
<br />
== Plasma ==<br />
<br />
;[[Development/Tutorials/Plasma/GettingStarted|Kuinka aloitetaan Plasmoidit]]<br />
:''Luo ensimmäinen Plasma-käyttöliittymäkomponenttisi tai Plasmoid, C++:ssa SVG-taustalla, kuvakkeella ja jollain tekstillä.''<br />
<br />
;[[Development/Tutorials/Plasma/DataEngines|Kirjoitetaan DataEngine-rajapinta]]<br />
:''DataEngine-rajapinnat tarjoavat vakioidun rajapinnan eri data-lähteisiin käytettäväksi visualisoinneille. Opi mitä DataEngine-rajapinta on ja kuinka oma rajapinta kirjoitetaan.''<br />
<br />
;[[Development/Tutorials/Plasma/UsingDataEngines|Käytetään DataEngine-rajapintoja Plasmoideissa]]<br />
:''DataEngine-rajapinnalla on mahdollista hakea dataa näytölle yksinkertaisella ja vakioidulla tavalla. Tämä opastusohje kattaa aiheen, kuinka DataEngine-rajapintoja käytetään tähän tarkoitukseen Plasmoideissa.''<br />
<br />
;[[Development/Tutorials/Plasma/AbstractRunner|Luodaan Runners-lisäosia]]<br />
:''Runners-lisäosat tarjoavat toimintaperustaisen hakutoiminnon Plasma-työtilan "suorita komento"-valintaikkunassa. Mikä tahansa sovellus, joka linkitetään libplasma-kirjastoon, voi käyttää näitä lisäosia.''<br />
<br />
== Kate / Kwrite ==<br />
<br />
;[[Development/Tutorials/Kate/KTextEditor Plugins|Kuinka aloitetaan KTextEditor-lis&auml;osakehitys]]<br />
:''Luo ensimm&auml;inen KTextEditor-lis&auml;osasi''<br />
<br />
==Tulostus==<br />
<br />
;[[Development/Tutorials/Printing Hello World|Hei maailma!]]<br />
:''Perehdytys KDE-tulostusj&auml;rjestelm&auml;&auml;n''<br />
<br />
;[[Development/Tutorials/Printing Print Dialog|Tulostusviestiruutu]]<br />
:''Kuinka k&auml;ytet&auml;&auml;n KDE-tulostusviestiruutua''<br />
<br />
== Hae uutta kuumaa kamaa ==<br />
; [[Development/Tutorials/Introduction to Get Hot New Stuff|Johdatus uuden kuuman matskun hakemiseen]]<br />
:''Johdatus käyttäjäystävälliseen tietoverkkopäivitysjärjestelmään, joka sallii KDE-sovellusten noutaa uutta sovellusdataa ajoaikaisesti käyttäjäystävällisellä tavalla.''<br />
<br />
;[[Development/Tutorials/KNewStuffSecure|Suojattu KNewStuff-verkko]] ([http://developer.kde.org/documentation/tutorials/knewstuffsecure/index.html Alkuperäinen linkki])<br />
:''Opastusohje näyttää, kuinka jakaa resursseja suojatulla tavalla (KDE 3.4 ja myöhemmät versiot).'' Laatija Andr&#225;s Mantia &lt;amantia@kde.org&gt;.<br />
<br />
== Nopea sovelluskehitys ==<br />
<br />
=== Python ===<br />
<br />
;[[Development/Tutorials/Python introduction to signals and slots|101 Johdatus signaaleihin ja väleihin]]<br />
:''Yksinkertainen johdatus Qt-signaali- ja väliarkkitehtuuriin.''<br />
<br />
=== Ruby ===<br />
<br />
;[http://developer.kde.org/language-bindings/ruby/kde3tutorial/index.html KDE Ruby Korundum opastusohje]<br />
:''Antonio Larrosa Jim&eacute;nez:n kirjoittama Ruby-versio Richard Dalen kirjoittamasta KDE-perehdytyksest&auml;. Katso [http://developer.kde.org/language-bindings/ruby/index.html Ruby-kehitt&auml;jien nurkkaus] Qt-opastusohjeille ja muille tiedoille.''<br />
<br />
;[[Development/Tutorials/Qt4_Ruby_Tutorial|Qt4 Ruby-opas]]<br />
:''Trolltech:n kuuluisa alustava Qt-opas muunnettuna Ruby-perehdytykseksi.''<br />
<br />
=== Komentotulkki ===<br />
<br />
;[[Development/Tutorials/Shell_Scripting_with_KDE_Dialogs|KDE-valintaikkunoita käyttävät komentotulkkiskriptit]] ([http://developer.kde.org/documentation/tutorials/kdialog/t1.html Alkuperäinen linkki]) <br />
:''[mailto:bradh@frogmouth.net Brad Hards]:in kirjoittama opas,joka kuvailee kuinka KDE-valintaikkunoita käytetään komentotulkkikripteissä kdialogin avulla.''<br />
<br />
== Muita opastusohjeita ==<br />
<br />
=== KDE Games-kirjaston k&auml;ytt&ouml; ===<br />
;[[Development/Tutorials/Games/KStandardGameAction| KStandardGameAction]]<br />
:''Käytetään libkdegames-kirjastoa, jotta pelisi sopisi kdegames-standardiin''<br />
;[[Development/Tutorials/Games/Highscores| Parhaat pisteet]]<br />
:''Toteutetaan yksinkertainen "parhaat pisteet"-taulukko peliisi''<br />
;[[Development/Tutorials/Games/Theme Selector| Teemavalitsin]]<br />
:''Käytetään libkdegames-kirjaston teemavalitsin valintaikkunaa''<br />
<br />
=== 2D-tulostus (KPlotWidget) ===<br />
;[[Development/Tutorials/KPlotWidget|Using the KDE data-plotting widget]]<br />
:''This tutorial introduces KPlotWidget, which is used for 2-D data plotting. It includes information on simple usage of the widget (including adding and modifying data sets, and customizing the plot axes and labels), and advanced customization (including extending the widget through sub-classing).''<br />
<br />
=== Oikeinkirjoitus- ja kielioppitarkistus (Sonnet) ===<br />
;[[Development/Tutorials/Sonnet/SonnetTutorial|Oikeinkirjoitus- ja kielioppitarkistuksen lis&auml;&auml;minen KDE-sovelluksiin]]<br />
:''T&auml;m&auml; opastusohje esittelee Sonnet-ohjelman ja sen käytön KDE-sovelluksesi kielen korjaamiseen. Sonnet-ohjelman lis&auml;ominaisuudet kuvaillaan erillisess&auml; oppaassa.''<br />
<br />
=== Pixmap-v&auml;limuisti (KPixmapCache) ===<br />
;[[Development/Tutorials/KPixmapCache|KDE pixmap-v&auml;limuistin k&auml;ytt&ouml;]]<br />
:''T&auml;m&auml; opastusohje n&auml;ytt&auml;&auml; kuinka KPixmapCache:lla sijoitetaan SVG-yksikk&ouml;jen ja muun datan luomia pixmap-kuvia KDE-v&auml;limuistiin.''<br />
<br />
== KDE2- ja KDE3-materiaalit ==<br />
<br />
;[[Development/Tutorials/KDE3|KDE3-opastusohjeet]]<br />
:''N&auml;m&auml; ohjeet kattavat KDE3-aiheet.''<br />
<br />
;[[Development/Tutorials/KDE2|KDE2-opastusohjeet]]<br />
:''N&auml;m&auml; ohjeet kattavat KDE2-aiheet''<br />
<br />
[[Category:KDE4]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19534Development/Tutorials/Saving and loading (fi)2008-01-11T10:36:52Z<p>Ozzi: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Tallettaminen ja Avaaminen|<br />
<br />
pre=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Abstract==<br />
<br />
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 disc, save files that you've created/edited and create new files.<br />
<br />
KDE provides a number of classes for working with files which make life a lot easier for developers. The KIO library allows you to easily access files through network-transparent protocols as well as providing standard file dialogs.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== The Code ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt> hasn't changed from tutorial 3 except to change any reference to tutorial 3 to tutorial 4.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT //new from tutorial3<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; //new<br />
<br />
private slots: //new<br />
void newFile(); //new<br />
void openFile(); //new<br />
void saveFile(); //new<br />
void saveFileAs(); //new<br />
void saveFileAs(const QString &outputFileName); //new<br />
};<br />
<br />
#endif<br />
</code><br />
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.trolltech.com/latest/signalsandslots.html signal/slot] mechanism we must specify that these functions are slots as we do on line 19. Since we are using slots in this header file, we must also add the [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] macro.<br />
<br />
We also want to keep track of the filename of the currently opened file so we declare a <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> //new<br />
#include <KMessageBox> //new<br />
#include <KIO/NetAccess> //new<br />
#include <KSaveFile> //new<br />
#include <QTextStream> //new<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //new<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //new<br />
<br />
setupGUI();<br />
}<br />
<br />
//New from here on<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
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.<br />
<br />
==Explanation==<br />
<br />
Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt><br />
<br />
The first thing we do is add<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
to the <tt>MainWindow</tt> constructor list on line 16. This makes sure that <tt>fileName</tt> is empty right from the beginning.<br />
<br />
===Adding the actions===<br />
<br />
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.<br />
<br />
===Creating a new document===<br />
<br />
The first function we create is the <tt>newFile()</tt> function.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<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.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19532Development/Tutorials/Using KActions (fi)2008-01-11T10:35:32Z<p>Ozzi: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading (fi)|Perehdytys 4 - Tallettaminen ja Avaaminen]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
{{class|KXmlGuiWindow}}:n <tt>setupGUI()</tt>-funktion käyttöliittymän muodostus on riippuvainen XMLGUI-järjestelmästä joka hakee XML-tiedostosta käyttöliittymän muodostuksessa tarvittavat tiedot.<br />
<br />
XML tiedston nimeämissäännöt ovat riippuvaisia siitä ohjelmannimestä joka on asetettu {{class|KAboutData}}:ssa (tässä tapauksessa ''tutorial3'') siten että XML-toedostonimi muodostuu: ohjelmannimi + ''ui.rc'' (tässä tapauksessa siis ''tutorial3ui.rc'').<br />
<br />
==''ohjelmannimi''ui.rc - tiedosto==<br />
<br />
Koska käyttöliittymä on määritelty XML-tiedoston avulla, ulkoasun täytyy noudattaa tiettyjä sääntöjä. Tämä perehdytys ei paneudu kovin syvällisesti tähän aiheeseen. Lisätietoja: [[Development/Architecture/KDE4/XMLGUI_Technology|XMLGUI - Tekniikka]](tulossa ?).<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
<tt><Toolbar></tt>-kohdassa kuvaillaan ikkunan yläosassa, yleensä ikonein varusteltu, vaakasuuntainen laidasta laitaan sijaitseva työkalurivi. Tässä tapauksessa työkaluriville on annettu yksilöllinen nimi ''mainToolBar'' ja sen näkyvä nimi on asetettu <tt><text></tt>-merkinnällä ''Main Toolbar'':ksi. Tyhjennä-toiminto on asetettu työkaluriville <tt><Action></tt>-merkinnän avulla. Toiminnon nimi on sama joka aikasemmin lisättiin <tt>addAction()</tt>-funktion avulla toimintokokoelmaan <tt>mainwindow.cpp</tt>-tiedostossa.<br />
<br />
Toiminto on mahdollista lisätä myös valikkoriville. Tässä tapauksessa ''Tyhjennä'' toiminto on lisätty ''Tiedosto''(File) valikkoon, samalla tavalla kuin se lisättiin työkalurivillekkin.<br />
<br />
Muista vaihtaa 'version'-määrite(versionumero) <tt><nowiki><gui></nowiki></tt>-merkinnästä jos muutat .rc-tiedostoa saattaaksesi viimeisimmän asennuksen mukaisen version järjestelmänvälmuistiin.<br />
<br />
==CMake==<br />
Lopuksi <tt>tutorial3ui.rc</tt>-tiedosto täytyy sijoittaa jonnekkin mistä KDE voi sen löytää (sitä ei voi pelkästään jättää lähdehakemistoon). '''Tämä tarkoittaa että tämä projekti tarvitsee asentaa jonnekkin.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
Tämä tiedosto on lähes identtinen Perehdytys 2:n vastaavan kanssa. Ainoastaan tiedoston loppuun on lisätty kaksi uutta riviä jotka kertovat minne tiedostot tulee asentaa. <tt>tutorial3</tt>(suoritettava binääri, ohjelma) asennetaan hakemistoon joka on määritelty <tt>BIN_INSTALL_DIR</tt>-muttujassa ja <tt>tutorial3ui.rc</tt>-tiedosto joka siis määrittelee ohjelman ulkoasun, asennetaan ohjelman data-hakemistoon.<br />
<br />
===Käännä, Asenna ja Suorita===<br />
Jos sinulla ei ole kirjoitusoikeutta KDE4:n asennushakemistoon, voit asentaa ohjelmasi myös kotikansiossa olevaan hakemistoon.<br />
<br />
Kertoaksesi CMakelle, minne ohjelma tulee asentaa, tarvitsee käyttää <tt>DCMAKE_INSTALL_PREFIX</tt>-kytkintä. Luultavasti haluat asentaa nämä perehdytykset kotihakemistoosi (KDE asennushakemisto on oletuksena asennushakemisto) joten ehdotan seuraavaa:<br />
<code><br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME/kde4_harjoittelu<br />
make install<br />
$HOME/kde4_harjoittelu/bin/tutorial3<br />
</code><br />
Ylläoleva luo KDE-hakemistorakenteen kotihakemistosi kde_harjoittelu-hakemiston alle sekä asentaa ohjelman sinne oikeille paikoilleen.<br />
<br />
==Seuraavaksi==<br />
Nyt olet valmis siirtymään eteenpäin [[Development/Tutorials/Saving_and_loading (fi)|Perehdytys 4 - Tallettaminen ja Avaaminen]]-kohtaan.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Saving_and_loading_(fi)&diff=19531Development/Tutorials/Saving and loading (fi)2008-01-11T10:34:36Z<p>Ozzi: Tästä se alkaa</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Saving_and_loading}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Loading and saving files|<br />
<br />
pre=[[Development/Tutorials/Using_KActions|Tutorial 3 - KActions]]|<br />
<br />
next=[[Development/Tutorials/KCmdLineArgs|Tutorial 5 - Using KCmdLineArgs]]| <br />
<br />
reading=KIO::{{class|NetAccess}} {{qt|QFile}}<br />
}}<br />
<br />
==Abstract==<br />
<br />
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 disc, save files that you've created/edited and create new files.<br />
<br />
KDE provides a number of classes for working with files which make life a lot easier for developers. The KIO library allows you to easily access files through network-transparent protocols as well as providing standard file dialogs.<br />
<br />
[[image:introtokdetutorial4.png|frame|center]]<br />
<br />
== The Code ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial4", "tutorial4",<br />
ki18n("Tutorial 4"), "1.0",<br />
ki18n("A simple text area which can load and save."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
<tt>main.cpp</tt> hasn't changed from tutorial 3 except to change any reference to tutorial 3 to tutorial 4.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
Q_OBJECT //new from tutorial3<br />
<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
QString fileName; //new<br />
<br />
private slots: //new<br />
void newFile(); //new<br />
void openFile(); //new<br />
void saveFile(); //new<br />
void saveFileAs(); //new<br />
void saveFileAs(const QString &outputFileName); //new<br />
};<br />
<br />
#endif<br />
</code><br />
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.trolltech.com/latest/signalsandslots.html signal/slot] mechanism we must specify that these functions are slots as we do on line 19. Since we are using slots in this header file, we must also add the [http://doc.trolltech.com/latest/qobject.html#Q_OBJECT <tt>Q_OBJECT</tt>] macro.<br />
<br />
We also want to keep track of the filename of the currently opened file so we declare a <tt>{{qt|QString}} fileName</tt>.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
#include <KFileDialog> //new<br />
#include <KMessageBox> //new<br />
#include <KIO/NetAccess> //new<br />
#include <KSaveFile> //new<br />
#include <QTextStream> //new<br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent),<br />
fileName(QString()) //new<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
KStandardAction::open(this, SLOT(openFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::save(this, SLOT(saveFile()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::saveAs(this, SLOT(saveFileAs()),<br />
actionCollection()); //new<br />
<br />
KStandardAction::openNew(this, SLOT(newFile()),<br />
actionCollection()); //new<br />
<br />
setupGUI();<br />
}<br />
<br />
//New from here on<br />
<br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
<br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
{<br />
KSaveFile file(outputFileName);<br />
file.open();<br />
<br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
<br />
fileName = outputFileName;<br />
}<br />
<br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
<br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
<br />
void MainWindow::openFile()<br />
{<br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
<br />
QString tmpFile;<br />
if(KIO::NetAccess::download(fileNameFromDialog, tmpFile, <br />
this))<br />
{<br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
fileName = fileNameFromDialog;<br />
<br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
}<br />
else<br />
{<br />
KMessageBox::error(this, <br />
KIO::NetAccess::lastErrorString());<br />
}<br />
}<br />
</code><br />
<br />
===tutorial4ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial4" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
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.<br />
<br />
==Explanation==<br />
<br />
Okay, now to implement the code that will do the loading and saving. This will all be happening in <tt>mainwindow.cpp</tt><br />
<br />
The first thing we do is add<br />
<code cppqt><br />
fileName(QString())<br />
</code><br />
to the <tt>MainWindow</tt> constructor list on line 16. This makes sure that <tt>fileName</tt> is empty right from the beginning.<br />
<br />
===Adding the actions===<br />
<br />
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.<br />
<br />
===Creating a new document===<br />
<br />
The first function we create is the <tt>newFile()</tt> function.<br />
<code cppqt><br />
void MainWindow::newFile()<br />
{<br />
fileName.clear();<br />
textArea->clear();<br />
}<br />
</code><br />
<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.<br />
<br />
===Saving a file===<br />
<br />
====saveFileAs(QString)====<br />
<br />
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}}.<br />
<br />
The function's prototype is<br />
<code cppqt><br />
void MainWindow::saveFileAs(const QString &outputFileName)<br />
</code><br />
<br />
We then create our <tt>KSaveFile</tt> object and open it with<br />
<code cppqt><br />
KSaveFile file(outputFileName);<br />
file.open();<br />
</code><br />
<br />
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:<br />
<code cppqt><br />
QByteArray outputByteArray;<br />
outputByteArray.append(textArea->toPlainText());<br />
</code><br />
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.<br />
<code cppqt><br />
file.write(outputByteArray);<br />
file.finalize();<br />
file.close();<br />
</code><br />
Finally, we set <tt>MainWindows</tt>'s <tt>fileName</tt> member to point to the file name we just saved to.<br />
<code cppqt><br />
fileName = outputFileName;<br />
</code><br />
<br />
====saveFileAs()====<br />
<br />
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>.<br />
<br />
<code cppqt><br />
void MainWindow::saveFileAs()<br />
{<br />
saveFileAs(KFileDialog::getSaveFileName());<br />
}<br />
</code><br />
<br />
This 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>.<br />
<br />
====saveFile()====<br />
<br />
<code cppqt><br />
void MainWindow::saveFile()<br />
{<br />
if(!fileName.isEmpty())<br />
{<br />
saveFileAs(fileName);<br />
}<br />
else<br />
{<br />
saveFileAs();<br />
}<br />
}<br />
</code><br />
<br />
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.<br />
<br />
===Loading a file===<br />
<br />
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>.<br />
<br />
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>:<br />
<code cppqt><br />
QString fileNameFromDialog = KFileDialog::getOpenFileName();<br />
</code><br />
<br />
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<br />
<code cppqt><br />
KIO::NetAccess::download(fileNameFromDialog, tmpFile, this)<br />
</code><br />
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.<br />
<br />
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:<br />
<code cppqt><br />
KMessageBox::error(this, KIO::NetAccess::lastErrorString());<br />
</code><br />
<br />
Otherwise, we continue with opening the file.<br />
<br />
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<br />
<code cppqt><br />
QFile file(tmpFile);<br />
file.open(QIODevice::ReadOnly);<br />
</code><br />
<br />
In order to display the contents of the file, we must use a {{class|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.<br />
<br />
<code cppqt><br />
textArea->setPlainText(QTextStream(&file).readAll());<br />
</code><br />
<br />
We then store the path of the file we just opened:<br />
<code cppqt><br />
fileName = fileNameFromDialog;<br />
</code><br />
and finally, we remove the temporary file that was created by <tt>NetAccess::download()</tt>:<br />
<code cppqt><br />
KIO::NetAccess::removeTempFile(tmpFile);<br />
</code><br />
<br />
==Make, Install And Run==<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial4)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial4_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial4 ${tutorial4_SRCS})<br />
<br />
target_link_libraries(tutorial4 ${KDE4_KDEUI_LIBS} <br />
${KDE4_KIO_LIBS})<br />
<br />
install(TARGETS tutorial4 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial4ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial4)<br />
</code><br />
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.<br />
<br />
With this file, the tutorial can built and run in the same way as tutorial 3. For more information, see tutorial 3.<br />
<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial4<br />
<br />
==Moving On==<br />
Now you can move on to the [[Development/Tutorials/KCmdLineArgs|KCmdLineArgs]] tutorial.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19530Development/Tutorials/Using KActions (fi)2008-01-11T10:33:19Z<p>Ozzi: /* Moving On */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
{{class|KXmlGuiWindow}}:n <tt>setupGUI()</tt>-funktion käyttöliittymän muodostus on riippuvainen XMLGUI-järjestelmästä joka hakee XML-tiedostosta käyttöliittymän muodostuksessa tarvittavat tiedot.<br />
<br />
XML tiedston nimeämissäännöt ovat riippuvaisia siitä ohjelmannimestä joka on asetettu {{class|KAboutData}}:ssa (tässä tapauksessa ''tutorial3'') siten että XML-toedostonimi muodostuu: ohjelmannimi + ''ui.rc'' (tässä tapauksessa siis ''tutorial3ui.rc'').<br />
<br />
==''ohjelmannimi''ui.rc - tiedosto==<br />
<br />
Koska käyttöliittymä on määritelty XML-tiedoston avulla, ulkoasun täytyy noudattaa tiettyjä sääntöjä. Tämä perehdytys ei paneudu kovin syvällisesti tähän aiheeseen. Lisätietoja: [[Development/Architecture/KDE4/XMLGUI_Technology|XMLGUI - Tekniikka]](tulossa ?).<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
<tt><Toolbar></tt>-kohdassa kuvaillaan ikkunan yläosassa, yleensä ikonein varusteltu, vaakasuuntainen laidasta laitaan sijaitseva työkalurivi. Tässä tapauksessa työkaluriville on annettu yksilöllinen nimi ''mainToolBar'' ja sen näkyvä nimi on asetettu <tt><text></tt>-merkinnällä ''Main Toolbar'':ksi. Tyhjennä-toiminto on asetettu työkaluriville <tt><Action></tt>-merkinnän avulla. Toiminnon nimi on sama joka aikasemmin lisättiin <tt>addAction()</tt>-funktion avulla toimintokokoelmaan <tt>mainwindow.cpp</tt>-tiedostossa.<br />
<br />
Toiminto on mahdollista lisätä myös valikkoriville. Tässä tapauksessa ''Tyhjennä'' toiminto on lisätty ''Tiedosto''(File) valikkoon, samalla tavalla kuin se lisättiin työkalurivillekkin.<br />
<br />
Muista vaihtaa 'version'-määrite(versionumero) <tt><nowiki><gui></nowiki></tt>-merkinnästä jos muutat .rc-tiedostoa saattaaksesi viimeisimmän asennuksen mukaisen version järjestelmänvälmuistiin.<br />
<br />
==CMake==<br />
Lopuksi <tt>tutorial3ui.rc</tt>-tiedosto täytyy sijoittaa jonnekkin mistä KDE voi sen löytää (sitä ei voi pelkästään jättää lähdehakemistoon). '''Tämä tarkoittaa että tämä projekti tarvitsee asentaa jonnekkin.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
Tämä tiedosto on lähes identtinen Perehdytys 2:n vastaavan kanssa. Ainoastaan tiedoston loppuun on lisätty kaksi uutta riviä jotka kertovat minne tiedostot tulee asentaa. <tt>tutorial3</tt>(suoritettava binääri, ohjelma) asennetaan hakemistoon joka on määritelty <tt>BIN_INSTALL_DIR</tt>-muttujassa ja <tt>tutorial3ui.rc</tt>-tiedosto joka siis määrittelee ohjelman ulkoasun, asennetaan ohjelman data-hakemistoon.<br />
<br />
===Käännä, Asenna ja Suorita===<br />
Jos sinulla ei ole kirjoitusoikeutta KDE4:n asennushakemistoon, voit asentaa ohjelmasi myös kotikansiossa olevaan hakemistoon.<br />
<br />
Kertoaksesi CMakelle, minne ohjelma tulee asentaa, tarvitsee käyttää <tt>DCMAKE_INSTALL_PREFIX</tt>-kytkintä. Luultavasti haluat asentaa nämä perehdytykset kotihakemistoosi (KDE asennushakemisto on oletuksena asennushakemisto) joten ehdotan seuraavaa:<br />
<code><br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME/kde4_harjoittelu<br />
make install<br />
$HOME/kde4_harjoittelu/bin/tutorial3<br />
</code><br />
Ylläoleva luo KDE-hakemistorakenteen kotihakemistosi kde_harjoittelu-hakemiston alle sekä asentaa ohjelman sinne oikeille paikoilleen.<br />
<br />
==Seuraavaksi==<br />
Nyt olet valmis siirtymään eteenpäin [[Development/Tutorials/Saving_and_loading (fi)|Perehdytys 4 - Tallettaminen ja Avaaminen]]-kohtaan.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19529Development/Tutorials/Using KActions (fi)2008-01-11T10:31:27Z<p>Ozzi: /* Make, Install And Run */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
{{class|KXmlGuiWindow}}:n <tt>setupGUI()</tt>-funktion käyttöliittymän muodostus on riippuvainen XMLGUI-järjestelmästä joka hakee XML-tiedostosta käyttöliittymän muodostuksessa tarvittavat tiedot.<br />
<br />
XML tiedston nimeämissäännöt ovat riippuvaisia siitä ohjelmannimestä joka on asetettu {{class|KAboutData}}:ssa (tässä tapauksessa ''tutorial3'') siten että XML-toedostonimi muodostuu: ohjelmannimi + ''ui.rc'' (tässä tapauksessa siis ''tutorial3ui.rc'').<br />
<br />
==''ohjelmannimi''ui.rc - tiedosto==<br />
<br />
Koska käyttöliittymä on määritelty XML-tiedoston avulla, ulkoasun täytyy noudattaa tiettyjä sääntöjä. Tämä perehdytys ei paneudu kovin syvällisesti tähän aiheeseen. Lisätietoja: [[Development/Architecture/KDE4/XMLGUI_Technology|XMLGUI - Tekniikka]](tulossa ?).<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
<tt><Toolbar></tt>-kohdassa kuvaillaan ikkunan yläosassa, yleensä ikonein varusteltu, vaakasuuntainen laidasta laitaan sijaitseva työkalurivi. Tässä tapauksessa työkaluriville on annettu yksilöllinen nimi ''mainToolBar'' ja sen näkyvä nimi on asetettu <tt><text></tt>-merkinnällä ''Main Toolbar'':ksi. Tyhjennä-toiminto on asetettu työkaluriville <tt><Action></tt>-merkinnän avulla. Toiminnon nimi on sama joka aikasemmin lisättiin <tt>addAction()</tt>-funktion avulla toimintokokoelmaan <tt>mainwindow.cpp</tt>-tiedostossa.<br />
<br />
Toiminto on mahdollista lisätä myös valikkoriville. Tässä tapauksessa ''Tyhjennä'' toiminto on lisätty ''Tiedosto''(File) valikkoon, samalla tavalla kuin se lisättiin työkalurivillekkin.<br />
<br />
Muista vaihtaa 'version'-määrite(versionumero) <tt><nowiki><gui></nowiki></tt>-merkinnästä jos muutat .rc-tiedostoa saattaaksesi viimeisimmän asennuksen mukaisen version järjestelmänvälmuistiin.<br />
<br />
==CMake==<br />
Lopuksi <tt>tutorial3ui.rc</tt>-tiedosto täytyy sijoittaa jonnekkin mistä KDE voi sen löytää (sitä ei voi pelkästään jättää lähdehakemistoon). '''Tämä tarkoittaa että tämä projekti tarvitsee asentaa jonnekkin.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
Tämä tiedosto on lähes identtinen Perehdytys 2:n vastaavan kanssa. Ainoastaan tiedoston loppuun on lisätty kaksi uutta riviä jotka kertovat minne tiedostot tulee asentaa. <tt>tutorial3</tt>(suoritettava binääri, ohjelma) asennetaan hakemistoon joka on määritelty <tt>BIN_INSTALL_DIR</tt>-muttujassa ja <tt>tutorial3ui.rc</tt>-tiedosto joka siis määrittelee ohjelman ulkoasun, asennetaan ohjelman data-hakemistoon.<br />
<br />
===Käännä, Asenna ja Suorita===<br />
Jos sinulla ei ole kirjoitusoikeutta KDE4:n asennushakemistoon, voit asentaa ohjelmasi myös kotikansiossa olevaan hakemistoon.<br />
<br />
Kertoaksesi CMakelle, minne ohjelma tulee asentaa, tarvitsee käyttää <tt>DCMAKE_INSTALL_PREFIX</tt>-kytkintä. Luultavasti haluat asentaa nämä perehdytykset kotihakemistoosi (KDE asennushakemisto on oletuksena asennushakemisto) joten ehdotan seuraavaa:<br />
<code><br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME/kde4_harjoittelu<br />
make install<br />
$HOME/kde4_harjoittelu/bin/tutorial3<br />
</code><br />
Ylläoleva luo KDE-hakemistorakenteen kotihakemistosi kde_harjoittelu-hakemiston alle sekä asentaa ohjelman sinne oikeille paikoilleen.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19524Development/Tutorials/Using KActions (fi)2008-01-11T10:10:04Z<p>Ozzi: /* CMakeLists.txt */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
{{class|KXmlGuiWindow}}:n <tt>setupGUI()</tt>-funktion käyttöliittymän muodostus on riippuvainen XMLGUI-järjestelmästä joka hakee XML-tiedostosta käyttöliittymän muodostuksessa tarvittavat tiedot.<br />
<br />
XML tiedston nimeämissäännöt ovat riippuvaisia siitä ohjelmannimestä joka on asetettu {{class|KAboutData}}:ssa (tässä tapauksessa ''tutorial3'') siten että XML-toedostonimi muodostuu: ohjelmannimi + ''ui.rc'' (tässä tapauksessa siis ''tutorial3ui.rc'').<br />
<br />
==''ohjelmannimi''ui.rc - tiedosto==<br />
<br />
Koska käyttöliittymä on määritelty XML-tiedoston avulla, ulkoasun täytyy noudattaa tiettyjä sääntöjä. Tämä perehdytys ei paneudu kovin syvällisesti tähän aiheeseen. Lisätietoja: [[Development/Architecture/KDE4/XMLGUI_Technology|XMLGUI - Tekniikka]](tulossa ?).<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
<tt><Toolbar></tt>-kohdassa kuvaillaan ikkunan yläosassa, yleensä ikonein varusteltu, vaakasuuntainen laidasta laitaan sijaitseva työkalurivi. Tässä tapauksessa työkaluriville on annettu yksilöllinen nimi ''mainToolBar'' ja sen näkyvä nimi on asetettu <tt><text></tt>-merkinnällä ''Main Toolbar'':ksi. Tyhjennä-toiminto on asetettu työkaluriville <tt><Action></tt>-merkinnän avulla. Toiminnon nimi on sama joka aikasemmin lisättiin <tt>addAction()</tt>-funktion avulla toimintokokoelmaan <tt>mainwindow.cpp</tt>-tiedostossa.<br />
<br />
Toiminto on mahdollista lisätä myös valikkoriville. Tässä tapauksessa ''Tyhjennä'' toiminto on lisätty ''Tiedosto''(File) valikkoon, samalla tavalla kuin se lisättiin työkalurivillekkin.<br />
<br />
Muista vaihtaa 'version'-määrite(versionumero) <tt><nowiki><gui></nowiki></tt>-merkinnästä jos muutat .rc-tiedostoa saattaaksesi viimeisimmän asennuksen mukaisen version järjestelmänvälmuistiin.<br />
<br />
==CMake==<br />
Lopuksi <tt>tutorial3ui.rc</tt>-tiedosto täytyy sijoittaa jonnekkin mistä KDE voi sen löytää (sitä ei voi pelkästään jättää lähdehakemistoon). '''Tämä tarkoittaa että tämä projekti tarvitsee asentaa jonnekkin.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
Tämä tiedosto on lähes identtinen Perehdytys 2:n vastaavan kanssa. Ainoastaan tiedoston loppuun on lisätty kaksi uutta riviä jotka kertovat minne tiedostot tulee asentaa. <tt>tutorial3</tt>(suoritettava binääri, ohjelma) asennetaan hakemistoon joka on määritelty <tt>BIN_INSTALL_DIR</tt>-muttujassa ja <tt>tutorial3ui.rc</tt>-tiedosto joka siis määrittelee ohjelman ulkoasun, asennetaan ohjelman data-hakemistoon.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19523Development/Tutorials/Using KActions (fi)2008-01-11T10:05:00Z<p>Ozzi: /* CMake */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
{{class|KXmlGuiWindow}}:n <tt>setupGUI()</tt>-funktion käyttöliittymän muodostus on riippuvainen XMLGUI-järjestelmästä joka hakee XML-tiedostosta käyttöliittymän muodostuksessa tarvittavat tiedot.<br />
<br />
XML tiedston nimeämissäännöt ovat riippuvaisia siitä ohjelmannimestä joka on asetettu {{class|KAboutData}}:ssa (tässä tapauksessa ''tutorial3'') siten että XML-toedostonimi muodostuu: ohjelmannimi + ''ui.rc'' (tässä tapauksessa siis ''tutorial3ui.rc'').<br />
<br />
==''ohjelmannimi''ui.rc - tiedosto==<br />
<br />
Koska käyttöliittymä on määritelty XML-tiedoston avulla, ulkoasun täytyy noudattaa tiettyjä sääntöjä. Tämä perehdytys ei paneudu kovin syvällisesti tähän aiheeseen. Lisätietoja: [[Development/Architecture/KDE4/XMLGUI_Technology|XMLGUI - Tekniikka]](tulossa ?).<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
<tt><Toolbar></tt>-kohdassa kuvaillaan ikkunan yläosassa, yleensä ikonein varusteltu, vaakasuuntainen laidasta laitaan sijaitseva työkalurivi. Tässä tapauksessa työkaluriville on annettu yksilöllinen nimi ''mainToolBar'' ja sen näkyvä nimi on asetettu <tt><text></tt>-merkinnällä ''Main Toolbar'':ksi. Tyhjennä-toiminto on asetettu työkaluriville <tt><Action></tt>-merkinnän avulla. Toiminnon nimi on sama joka aikasemmin lisättiin <tt>addAction()</tt>-funktion avulla toimintokokoelmaan <tt>mainwindow.cpp</tt>-tiedostossa.<br />
<br />
Toiminto on mahdollista lisätä myös valikkoriville. Tässä tapauksessa ''Tyhjennä'' toiminto on lisätty ''Tiedosto''(File) valikkoon, samalla tavalla kuin se lisättiin työkalurivillekkin.<br />
<br />
Muista vaihtaa 'version'-määrite(versionumero) <tt><nowiki><gui></nowiki></tt>-merkinnästä jos muutat .rc-tiedostoa saattaaksesi viimeisimmän asennuksen mukaisen version järjestelmänvälmuistiin.<br />
<br />
==CMake==<br />
Lopuksi <tt>tutorial3ui.rc</tt>-tiedosto täytyy sijoittaa jonnekkin mistä KDE voi sen löytää (sitä ei voi pelkästään jättää lähdehakemistoon). '''Tämä tarkoittaa että tämä projekti tarvitsee asentaa jonnekkin.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19522Development/Tutorials/Using KActions (fi)2008-01-11T10:02:28Z<p>Ozzi: /* tutorial3ui.rc */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
{{class|KXmlGuiWindow}}:n <tt>setupGUI()</tt>-funktion käyttöliittymän muodostus on riippuvainen XMLGUI-järjestelmästä joka hakee XML-tiedostosta käyttöliittymän muodostuksessa tarvittavat tiedot.<br />
<br />
XML tiedston nimeämissäännöt ovat riippuvaisia siitä ohjelmannimestä joka on asetettu {{class|KAboutData}}:ssa (tässä tapauksessa ''tutorial3'') siten että XML-toedostonimi muodostuu: ohjelmannimi + ''ui.rc'' (tässä tapauksessa siis ''tutorial3ui.rc'').<br />
<br />
==''ohjelmannimi''ui.rc - tiedosto==<br />
<br />
Koska käyttöliittymä on määritelty XML-tiedoston avulla, ulkoasun täytyy noudattaa tiettyjä sääntöjä. Tämä perehdytys ei paneudu kovin syvällisesti tähän aiheeseen. Lisätietoja: [[Development/Architecture/KDE4/XMLGUI_Technology|XMLGUI - Tekniikka]](tulossa ?).<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
<tt><Toolbar></tt>-kohdassa kuvaillaan ikkunan yläosassa, yleensä ikonein varusteltu, vaakasuuntainen laidasta laitaan sijaitseva työkalurivi. Tässä tapauksessa työkaluriville on annettu yksilöllinen nimi ''mainToolBar'' ja sen näkyvä nimi on asetettu <tt><text></tt>-merkinnällä ''Main Toolbar'':ksi. Tyhjennä-toiminto on asetettu työkaluriville <tt><Action></tt>-merkinnän avulla. Toiminnon nimi on sama joka aikasemmin lisättiin <tt>addAction()</tt>-funktion avulla toimintokokoelmaan <tt>mainwindow.cpp</tt>-tiedostossa.<br />
<br />
Toiminto on mahdollista lisätä myös valikkoriville. Tässä tapauksessa ''Tyhjennä'' toiminto on lisätty ''Tiedosto''(File) valikkoon, samalla tavalla kuin se lisättiin työkalurivillekkin.<br />
<br />
Muista vaihtaa 'version'-määrite(versionumero) <tt><nowiki><gui></nowiki></tt>-merkinnästä jos muutat .rc-tiedostoa saattaaksesi viimeisimmän asennuksen mukaisen version järjestelmänvälmuistiin.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19520Development/Tutorials/Using KActions (fi)2008-01-11T08:42:24Z<p>Ozzi: /* appnameui.rc File */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
{{class|KXmlGuiWindow}}:n <tt>setupGUI()</tt>-funktion käyttöliittymän muodostus on riippuvainen XMLGUI-järjestelmästä joka hakee XML-tiedostosta käyttöliittymän muodostuksessa tarvittavat tiedot.<br />
<br />
XML tiedston nimeämissäännöt ovat riippuvaisia siitä ohjelmannimestä joka on asetettu {{class|KAboutData}}:ssa (tässä tapauksessa ''tutorial3'') siten että XML-toedostonimi muodostuu: ohjelmannimi + ''ui.rc'' (tässä tapauksessa siis ''tutorial3ui.rc'').<br />
<br />
==''ohjelmannimi''ui.rc - tiedosto==<br />
<br />
Koska käyttöliittymä on määritelty XML-tiedoston avulla, ulkoasun täytyy noudattaa tiettyjä sääntöjä. Tämä perehdytys ei paneudu kovin syvällisesti tähän aiheeseen. Lisätietoja: [[Development/Architecture/KDE4/XMLGUI_Technology|XMLGUI - Tekniikka]](tulossa ?).<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19519Development/Tutorials/Using KActions (fi)2008-01-11T08:36:29Z<p>Ozzi: /* XMLGUI */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
{{class|KXmlGuiWindow}}:n <tt>setupGUI()</tt>-funktion käyttöliittymän muodostus on riippuvainen XMLGUI-järjestelmästä joka hakee XML-tiedostosta käyttöliittymän muodostuksessa tarvittavat tiedot.<br />
<br />
XML tiedston nimeämissäännöt ovat riippuvaisia siitä ohjelmannimestä joka on asetettu {{class|KAboutData}}:ssa (tässä tapauksessa ''tutorial3'') siten että XML-toedostonimi muodostuu: ohjelmannimi + ''ui.rc'' (tässä tapauksessa siis ''tutorial3ui.rc'').<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19518Development/Tutorials/Using KActions (fi)2008-01-11T08:34:44Z<p>Ozzi: /* XMLGUI */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
{{class|KXmlGuiWindow}}:n <tt>setupGUI()</tt>-funktion käyttöliittymän muodostus on riippuvainen XMLGUI-järjestelmästä joka hakee XML-tiedostosta käyttöliittymän muodostuksessa tarvittavat tiedot.<br />
<br />
XML tiedston nimeämissäännöt ovat riippuvaisia siitä ohjelmannimestä joka on asetettu {{class|KAboutData}}:ssa (tässä tapauksessa ''tutorial3'') siten että XML-toedostonimi muodostuu: ohjelmannimi + ''ui.rc'' (tässä tapauksessa siis ''tutorial3ui.rc''), ja se on sijoitettuna käännöshakemistoon. Tiedoston lopullisesta sijoituksesta huolehtii CMake.<br />
<br />
The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface. <br />
<br />
The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19489Development/Tutorials/Using KActions (fi)2008-01-10T20:56:57Z<p>Ozzi: /* Kokoelmaan lisääminen */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin myöhemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLGUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
<br />
The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface.<br />
<br />
The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19488Development/Tutorials/Using KActions (fi)2008-01-10T20:56:02Z<p>Ozzi: /* Kokoelmaan lis&auml;&auml;minen */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lisääminen===<br />
Jotta toimintoon olisi mahdollista päästä käsiksi XMLGUI-kehyksen(selitetty tarkemmin my&ouml;hemmin) läpi, se pitää lisätä ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa käsitellään <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Tässä <tt>clearAction</tt> KAction on lisätty kokoelmaan nimellä ''clear''. Nimeä (''clear'') on käytetään XMLQUI-kehyksessä kuvaamaan tätä toimintoa.<br />
<br />
====Toiminnon yhdistäminen====<br />
Kun toiminto on asetettu kuntoon, si pitää yhdistää johonkin joka toteuttaa toiminnon. Tässä tapauksessa (koska haluamme tyhjentää tekstialueen), yhdistämme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjentää tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Tämä sama voidaan tehdä Qt:n kanssa käyttämällä {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
<br />
The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface.<br />
<br />
The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19487Development/Tutorials/Using KActions (fi)2008-01-10T20:48:28Z<p>Ozzi: /* Adding the action to menus and toolbars */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lis&auml;&auml;minen===<br />
Jotta toimintoon olisi mahdollista p&auml;&auml;st&auml; k&auml;siksi XMLQUI-kehyksen(selitetty tarkemmin my&ouml;hemmin) l&auml;pi, se pit&auml;&auml; lis&auml;t&auml; ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa k&auml;sitell&auml;&auml;n <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
T&auml;ss&auml; <tt>clearAction</tt> KAction on lis&auml;tty kokoelmaan nimell&auml; ''clear''. Nime&auml; (''clear'') on k&auml;ytet&auml;&auml;n XMLQUI-kehyksess&auml; kuvaamaan t&auml;t&auml; toimintoa.<br />
<br />
====Toiminnon yhdist&auml;minen====<br />
Kun toiminto on asetettu kuntoon, si pit&auml;&auml; yhdist&auml;&auml; johonkin joka toteuttaa toiminnon. T&auml;ss&auml; tapauksessa (koska haluamme tyhjent&auml;&auml; tekstialueen), yhdist&auml;mme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjent&auml;&auml; tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
T&auml;m&auml; sama voidaan tehd&auml; Qt:n kanssa k&auml;ytt&auml;m&auml;ll&auml; {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Toiminnon lisääminen valikoihin ja työkaluriville==<br />
Tällä hetkellä, uusi "Tyhjennä" toiminto on luotu, mutta sitä ei ole vielä yhdistetty yhteenkään valikkoon tai työkaluriviin. Tähän tarkoitukseen käytämme KDE tekniikkaa nimeltään XMLGUI, jonka avulla voidaan toteuttaa mm. siirrettävät työkalurivit.<br />
<br />
{{note|Myöhemmissä KDE4 versioisssa XMLGUI-kehys saatetaan vaihtaa liveui-kehykseen, mutta tällä hetkellä XMLGUI on ainoa oikea tapa asettaa käyttöliittymä}}<br />
<br />
==XMLGUI==<br />
<br />
The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface.<br />
<br />
The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19485Development/Tutorials/Using KActions (fi)2008-01-10T20:27:39Z<p>Ozzi: /* KStandardAction */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lis&auml;&auml;minen===<br />
Jotta toimintoon olisi mahdollista p&auml;&auml;st&auml; k&auml;siksi XMLQUI-kehyksen(selitetty tarkemmin my&ouml;hemmin) l&auml;pi, se pit&auml;&auml; lis&auml;t&auml; ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa k&auml;sitell&auml;&auml;n <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
T&auml;ss&auml; <tt>clearAction</tt> KAction on lis&auml;tty kokoelmaan nimell&auml; ''clear''. Nime&auml; (''clear'') on k&auml;ytet&auml;&auml;n XMLQUI-kehyksess&auml; kuvaamaan t&auml;t&auml; toimintoa.<br />
<br />
====Toiminnon yhdist&auml;minen====<br />
Kun toiminto on asetettu kuntoon, si pit&auml;&auml; yhdist&auml;&auml; johonkin joka toteuttaa toiminnon. T&auml;ss&auml; tapauksessa (koska haluamme tyhjent&auml;&auml; tekstialueen), yhdist&auml;mme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjent&auml;&auml; tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
T&auml;m&auml; sama voidaan tehd&auml; Qt:n kanssa k&auml;ytt&auml;m&auml;ll&auml; {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
Toimintoja varten jotka esiintyvät lähes jokaisessa KDE ohjelmassa kuten 'sulje', 'tallenna' ja 'avaa' on olemassa valmiiksi luotuja sopivia toimintoja jotka on käytettävissä [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction]:n avulla.<br />
<br />
Nämä ovat erittäin helppoja ottaa käyttöön. Kun ensin on otettu kirjasto käyttöön (<tt>#include <KStandardAction></tt>), tarvitsee vain ottaa haluttu toiminto käyttöön, esim: <br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
Tämä luo ''Lopeta''-toiminnon, oikean ikonin, tekstin ja pikanäppäinyhdistelmän kanssa sekä jopa lisää sen Tiedosto-valikkoon.<br />
<br />
==Adding the action to menus and toolbars==<br />
At the moment, the new "Clear" action has been created but it hasn't been associated with any menus or toolbars. This is done with a KDE technology called XMLGUI, which does nice things like movable toolbars for you.<br />
<br />
{{note|In a later version of KDE4, XMLGUI, may be replaced with a new framework called liveui. For now, XMLGUI, is the only and correct way to set up the UI.}}<br />
<br />
==XMLGUI==<br />
<br />
The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface.<br />
<br />
The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=User_talk:Ozzi&diff=19484User talk:Ozzi2008-01-10T20:27:22Z<p>Ozzi: </p>
<hr />
<div>Hi Ozzi, I'm curious why you are replacing ä with &amp;auml; for example. The wiki itself supports UTF8 and äüößå... should work well. Do you have e.g. encoding problems? --[[User:Dhaumann|Dhaumann]] 20:42, 10 January 2008 (CET)<br />
<br />
== &amp;auml;s.. ==<br />
<br />
Well, I didn't any probs, but I didn't sure that is there any prob with skandinavian letters so I just translated them for sure. But thanks for advice! :)</div>Ozzihttps://techbase.kde.org/index.php?title=User_talk:Ozzi&diff=19483User talk:Ozzi2008-01-10T20:25:23Z<p>Ozzi: /* &auml;s.. */ new section</p>
<hr />
<div>Hi Ozzi, I'm curious why you are replacing ä with &amp;auml; for example. The wiki itself supports UTF8 and äüößå... should work well. Do you have e.g. encoding problems? --[[User:Dhaumann|Dhaumann]] 20:42, 10 January 2008 (CET)<br />
<br />
== &auml;s.. ==<br />
<br />
Well, I didn't any probs, but I didn't sure that is there any prob with skandinavian letters so I just translated them for sure. But thanks for advice! :)</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19482Development/Tutorials/Using KActions (fi)2008-01-10T20:09:22Z<p>Ozzi: /* Adding to the Collection */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Kokoelmaan lis&auml;&auml;minen===<br />
Jotta toimintoon olisi mahdollista p&auml;&auml;st&auml; k&auml;siksi XMLQUI-kehyksen(selitetty tarkemmin my&ouml;hemmin) l&auml;pi, se pit&auml;&auml; lis&auml;t&auml; ohjelman ''toiminto kokoelmaan''. Toimintokokoelmaa k&auml;sitell&auml;&auml;n <tt>actionCollection()</tt>-funktion avulla seuraavasti:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
T&auml;ss&auml; <tt>clearAction</tt> KAction on lis&auml;tty kokoelmaan nimell&auml; ''clear''. Nime&auml; (''clear'') on k&auml;ytet&auml;&auml;n XMLQUI-kehyksess&auml; kuvaamaan t&auml;t&auml; toimintoa.<br />
<br />
====Toiminnon yhdist&auml;minen====<br />
Kun toiminto on asetettu kuntoon, si pit&auml;&auml; yhdist&auml;&auml; johonkin joka toteuttaa toiminnon. T&auml;ss&auml; tapauksessa (koska haluamme tyhjent&auml;&auml; tekstialueen), yhdist&auml;mme toiminnon KTextEdit:n kuuluvaan <tt>clear()</tt>-funktioon (joka tyhjent&auml;&auml; tekstialueen) seuraavasti:<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
T&auml;m&auml; sama voidaan tehd&auml; Qt:n kanssa k&auml;ytt&auml;m&auml;ll&auml; {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
For actions which would likely appear in almost every KDE application such as 'quit', 'save', and 'load' there are pre-created convenience KActions, accessed through [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction].<br />
<br />
They are very simple to use. Once the library has been included (<tt>#include <KStandardAction></tt>), simply supply it with what you want the function to do and which KActionCollection to add it to. For example:<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
This creates a KAction with the correct icon, text and shortcut and even adds it to the File menu.<br />
<br />
==Adding the action to menus and toolbars==<br />
At the moment, the new "Clear" action has been created but it hasn't been associated with any menus or toolbars. This is done with a KDE technology called XMLGUI, which does nice things like movable toolbars for you.<br />
<br />
{{note|In a later version of KDE4, XMLGUI, may be replaced with a new framework called liveui. For now, XMLGUI, is the only and correct way to set up the UI.}}<br />
<br />
==XMLGUI==<br />
<br />
The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface.<br />
<br />
The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19481Development/Tutorials/Using KActions (fi)2008-01-10T19:56:00Z<p>Ozzi: /* mainwindow.h */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> jossa tehdään kaikki tarvittavat asettelut toimintoa varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Adding to the Collection===<br />
In order for the action to be accessed by the XMLGUI framework (explained in depth later) it must be added to the application's ''action collection''. The action collection is accessed via the <tt>actionCollection()</tt> function like this: <br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Here, the <tt>clearAction</tt> KAction is added to the collection and given a name of ''clear''. This name (''clear'') is used by the XMLGUI framework to refer to the action.<br />
<br />
====Connecting the action====<br />
Now that the action is fully set up, it needs to be connected to something useful. In this case (because we want to clear the text area), we connect our action to the <tt>clear()</tt> action belonging to a KTextEdit (which, unsurprisingly, clears the KTextEdit)<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
This is the same as it would be done in Qt with a {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
For actions which would likely appear in almost every KDE application such as 'quit', 'save', and 'load' there are pre-created convenience KActions, accessed through [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction].<br />
<br />
They are very simple to use. Once the library has been included (<tt>#include <KStandardAction></tt>), simply supply it with what you want the function to do and which KActionCollection to add it to. For example:<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
This creates a KAction with the correct icon, text and shortcut and even adds it to the File menu.<br />
<br />
==Adding the action to menus and toolbars==<br />
At the moment, the new "Clear" action has been created but it hasn't been associated with any menus or toolbars. This is done with a KDE technology called XMLGUI, which does nice things like movable toolbars for you.<br />
<br />
{{note|In a later version of KDE4, XMLGUI, may be replaced with a new framework called liveui. For now, XMLGUI, is the only and correct way to set up the UI.}}<br />
<br />
==XMLGUI==<br />
<br />
The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface.<br />
<br />
The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19480Development/Tutorials/Using KActions (fi)2008-01-10T19:53:27Z<p>Ozzi: /* N&auml;pp&auml;inyhdistelm&auml; */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> joka tekee kaiken tarvittavan asettelun KActions:a varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====Pikan&auml;pp&auml;inyhdistelm&auml;====<br />
Pikan&auml;pp&auml;inyhdistelm&auml;n asettaminen toiminnollemme on yht&auml;lailla helppo. Seuraava koodi osoittaa yhdistelm&auml;n Ctrl+W clearAction toiminnolle:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
<br />
===Adding to the Collection===<br />
In order for the action to be accessed by the XMLGUI framework (explained in depth later) it must be added to the application's ''action collection''. The action collection is accessed via the <tt>actionCollection()</tt> function like this: <br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Here, the <tt>clearAction</tt> KAction is added to the collection and given a name of ''clear''. This name (''clear'') is used by the XMLGUI framework to refer to the action.<br />
<br />
====Connecting the action====<br />
Now that the action is fully set up, it needs to be connected to something useful. In this case (because we want to clear the text area), we connect our action to the <tt>clear()</tt> action belonging to a KTextEdit (which, unsurprisingly, clears the KTextEdit)<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
This is the same as it would be done in Qt with a {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
For actions which would likely appear in almost every KDE application such as 'quit', 'save', and 'load' there are pre-created convenience KActions, accessed through [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction].<br />
<br />
They are very simple to use. Once the library has been included (<tt>#include <KStandardAction></tt>), simply supply it with what you want the function to do and which KActionCollection to add it to. For example:<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
This creates a KAction with the correct icon, text and shortcut and even adds it to the File menu.<br />
<br />
==Adding the action to menus and toolbars==<br />
At the moment, the new "Clear" action has been created but it hasn't been associated with any menus or toolbars. This is done with a KDE technology called XMLGUI, which does nice things like movable toolbars for you.<br />
<br />
{{note|In a later version of KDE4, XMLGUI, may be replaced with a new framework called liveui. For now, XMLGUI, is the only and correct way to set up the UI.}}<br />
<br />
==XMLGUI==<br />
<br />
The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface.<br />
<br />
The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(fi)&diff=19479Development/Tutorials/Using KActions (fi)2008-01-10T19:50:54Z<p>Ozzi: /* Ikoni */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 3 - KActions ja XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]], XML perustietous|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]| <br />
<br />
reading=None<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys esittelee toiminnot. Toiminnot tarjoavat yhten&auml;isen tavan k&auml;ytt&auml;j&auml;lle vuorovaikuttaa ohjelman kanssa.<br />
<br />
Jos esimerkiksi haluamme antaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|perehdytyksess&auml; 3 ]] k&auml;ytt&auml;jlle mahdollisuuden tyhjent&auml;&auml; tekstieditori hiiren n&auml;p&auml;ytyksell&auml; ty&ouml;kalurivilt&auml;, vaihtoehtoisesti Tiedosto-valikon kautta tai n&auml;pp&auml;inyhdistelm&auml;n avulla, voidaan t&auml;m&auml; tehd&auml; helposti k&auml;ytt&auml;m&auml;ll&auml; {{class|KAction}}-luokkaa.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
{{class|KAction}} on objekti joka sis&auml;lt&auml;&auml; kaiken tarvittavan tiedon ikonista ja n&auml;pp&auml;inyhdistelmist&auml; jotka on yhdistetty joihinkin toimintoon. Toiminto taas on yhdistetty [http://doc.trolltech.com/latest/signalsandslots.html slot]:n joka huolehtii toiminnon suorittamisesta.<br />
<br />
== Koodi ==<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial3", "tutorial3",<br />
ki18n("Tutorial 3"), "1.0",<br />
ki18n("A simple text area using KAction etc."),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
return app.exec();<br />
}<br />
</code><br />
T&auml;ll&auml; kerralla muutokset t&auml;h&auml;n tiedostoon ovat hyvin v&auml;h&auml;isi&auml;. Ainoastaan "tutorial 2" on korjattu "tutorial 3".<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
void setupActions();<br />
};<br />
<br />
#endif<br />
</code><br />
Otsikkotiedostoon on lis&auml;tty <tt>void setupActions()</tt> joka tekee kaiken tarvittavan asettelun KActions:a varten.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
#include <KApplication><br />
#include <KAction><br />
#include <KLocale><br />
#include <KActionCollection><br />
#include <KStandardAction><br />
<br />
MainWindow::MainWindow(QWidget *parent)<br />
: KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit;<br />
setCentralWidget(textArea);<br />
<br />
setupActions();<br />
}<br />
<br />
void MainWindow::setupActions()<br />
{<br />
KAction* clearAction = new KAction(this);<br />
clearAction->setText(i18n("Clear"));<br />
clearAction->setIcon(KIcon("document-new"));<br />
clearAction->setShortcut(Qt::CTRL + Qt::Key_W);<br />
actionCollection()->addAction("clear", clearAction);<br />
connect(clearAction, SIGNAL(triggered(bool)),<br />
textArea, SLOT(clear()));<br />
<br />
KStandardAction::quit(kapp, SLOT(quit()),<br />
actionCollection());<br />
<br />
setupGUI();<br />
}<br />
</code><br />
<br />
==Selvitys==<br />
T&auml;m&auml; perehdytys perustuu [[Development/Tutorials/Using_KXmlGuiWindow (fi)|edelliseen perehdytykseen]]. Suurin osa koodi muutoksista on <tt>mainwindow.cpp</tt> tiedostossa. Muodostajassa kutsutaan nyt <tt>setupActions()</tt> <tt>setupGUI()</tt> sijaan. <tt>setupActions()</tt>:ssa sijaitsee uusi KAction koodi joka lopuksi kutsuu <tt>setupGUI()</tt>-funktiota.<br />
<br />
===KAction objektin luominen===<br />
KActionin k&auml;ytt&ouml;&ouml;notossa on muutamia vaiheita. Ensimm&auml;inen on sis&auml;llytt&auml;&auml; <tt>KAction</tt>-kirjasto ja luoda uusi <tt>KAction</tt>:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
<br />
===KAction:n ominaisuuksien asettelu===<br />
====Teksti====<br />
Nyt meill&auml; siis on KAction objekti, joten voimme alkaa muokkaamaan sen ominaisuuksia. Seuraava koodi asettaa tekstin joka n&auml;ytet&auml;&auml;n valikossa sek&auml; ty&ouml;kaluvalikossa olevan ikonin alapuolella.<br />
<code cppqt><br />
clearAction->setText(i18n("Clear"));<br />
</code><br />
Huomaa ett&auml; teksti on sy&ouml;tetty i18n()-funktionin l&auml;pi. T&auml;m&auml; on pakollinen jotta k&auml;ytt&ouml;liittym&auml; on k&auml;&auml;nnett&auml;viss&auml; eri kielille. Lis&auml;tietoja lokalisoinnista l&ouml;ytyy [[Development/Tutorials/Localization/i18n|i18n perehdytyksest&auml;]]).<br />
<br />
====Ikoni====<br />
Jos toiminto on aikomus n&auml;ytt&auml;&auml; työkalurivill&auml;, olisi hyv&auml; jos sill&auml; olisi toimintoa kuvaava ikoni. Seuraava koodi asettaa standardin KDE <tt>document-new</tt>(Uusi asiakirja) ikonin clearAction toiminnolle:<br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
====N&auml;pp&auml;inyhdistelm&auml;====<br />
Setting a keyboard shortcut to perform our action is equally simple:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
This associates Ctrl+W with the KAction.<br />
<br />
===Adding to the Collection===<br />
In order for the action to be accessed by the XMLGUI framework (explained in depth later) it must be added to the application's ''action collection''. The action collection is accessed via the <tt>actionCollection()</tt> function like this: <br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Here, the <tt>clearAction</tt> KAction is added to the collection and given a name of ''clear''. This name (''clear'') is used by the XMLGUI framework to refer to the action.<br />
<br />
====Connecting the action====<br />
Now that the action is fully set up, it needs to be connected to something useful. In this case (because we want to clear the text area), we connect our action to the <tt>clear()</tt> action belonging to a KTextEdit (which, unsurprisingly, clears the KTextEdit)<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
This is the same as it would be done in Qt with a {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
For actions which would likely appear in almost every KDE application such as 'quit', 'save', and 'load' there are pre-created convenience KActions, accessed through [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction].<br />
<br />
They are very simple to use. Once the library has been included (<tt>#include <KStandardAction></tt>), simply supply it with what you want the function to do and which KActionCollection to add it to. For example:<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
This creates a KAction with the correct icon, text and shortcut and even adds it to the File menu.<br />
<br />
==Adding the action to menus and toolbars==<br />
At the moment, the new "Clear" action has been created but it hasn't been associated with any menus or toolbars. This is done with a KDE technology called XMLGUI, which does nice things like movable toolbars for you.<br />
<br />
{{note|In a later version of KDE4, XMLGUI, may be replaced with a new framework called liveui. For now, XMLGUI, is the only and correct way to set up the UI.}}<br />
<br />
==XMLGUI==<br />
<br />
The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface.<br />
<br />
The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.<br />
<br />
==''appname''ui.rc File==<br />
<br />
Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]].<br />
<br />
===tutorial3ui.rc===<br />
<code xml n><br />
<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"><br />
<gui name="tutorial3" version="1"><br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.<br />
<br />
Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.<br />
<br />
Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.<br />
<br />
==CMake==<br />
Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''<br />
===CMakeLists.txt===<br />
<code ini n><br />
project(tutorial3)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial3_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial3 ${tutorial3_SRCS})<br />
<br />
target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})<br />
<br />
install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})<br />
install(FILES tutorial3ui.rc <br />
DESTINATION ${DATA_INSTALL_DIR}/tutorial3)<br />
</code><br />
<br />
This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.<br />
<br />
===Make, Install And Run===<br />
If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.<br />
<br />
To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:<br />
mkdir build && cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME<br />
make install<br />
$HOME/bin/tutorial3<br />
which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/CMake_(fi)&diff=19478Development/Tutorials/CMake (fi)2008-01-10T19:44:29Z<p>Ozzi: /* autotools-pohjaisen KDE ohjelmiston k&auml;&auml;nt&auml;minen CMakelle */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/CMake}}<br />
<br />
== Esipuhe ==<br />
<br />
CMake tuottaa ohjaustiedostot j&auml;rjestelm&auml;n omalle k&auml;&auml;nt&auml;j&auml;lle omien komentotiedostojensa avulla. Se voi luoda GNU Makefilet, KDevelop-projektitiedostot, XCode-projektitiedostot, sek&auml; Visual Studio-projektitiedostot.<br />
<br />
CMake on vapaan l&auml;hdekoodin ohjelmisto joka on julkaistu BSD-tyylisen lisenssin alaisena. CMaken yll&auml;pit&auml;j&auml; on [http://www.kitware.com/ Kitware Inc.]<br />
<br />
N&auml;ist&auml; voit aloittaa CMaken perusteiden opiskelun (englanniksi):<br />
* [http://www.cmake.org/HTML/Documentation.html CMake Ohjekirja]<br />
* [http://www.cmake.org/Wiki/CMake CMake Wiki]<br />
* [http://www.cmake.org/Wiki/CMake_HowToDoPlatformChecks CMake - J&auml;rjestelm&auml;n Tarkistukset]<br />
* [http://www.cmake.org/Wiki/CMake_HowToFindInstalledSoftware CMake - Kuinka L&ouml;yt&auml;&auml; Asennetut Ohjelmat]<br />
* [http://www.cmake.org/Wiki/HowToBuildKDE4Software KDE 4 Perehdytys CMake Wikiss&auml;]<br />
* [http://www.cmake.org/Wiki/CMake_FAQ CMake FAQ]<br />
* [http://mail.kde.org/pipermail/kde-buildsystem/ Kde-buildsystem - Postituslistan arkisto]<br />
Voit my&ouml;s liitty&auml; CMake [http://www.cmake.org/mailman/listinfo/cmake postituslistalle].<br />
<br />
== Miksi k&auml;ytt&auml;&auml; CMakea ? ==<br />
<br />
Maaliskuussa 2006 p&auml;&auml;tettiin valita CMake KDE 4 julkaisun viralliseksi ty&ouml;kaluksi, p&auml;&auml;s&auml;&auml;nt&ouml;isesti sen teknisten ominaisuuksien vuoksi verrattuna vankempiin KDE ty&ouml;kaluihin kuten automake ja unsermake:<br />
<br />
* CMake on kehitetty KDE:st&auml; riippumattomana, ja sit&auml; voidaan k&auml;ytt&auml;&auml; my&ouml;s muissa projekteissa<br />
* K&auml;&auml;nn&ouml;sajat j&auml;&auml;v&auml;t paljon pienemmiksi, p&auml;&auml;osin koska libtoolia ei en&auml;&auml; tarvita<br />
* K&auml;&auml;nn&ouml;stiedostot ovat helpompia kirjoittaa<br />
<br />
== KDE:n k&auml;&auml;nt&auml;minen CMakea k&auml;ytt&auml;en ==<br />
=== Lataa ja asenna CMake ===<br />
==== Linux, BSD, sek&auml; muut Unix J&auml;rjestelm&auml;t ====<br />
Hae viimeisin vakaa versio CMakesta [http://www.cmake.org/HTML/Download.html t&auml;&auml;lt&auml;.]<br />
<br />
Pura ja k&auml;&auml;nn&auml;:<br />
<br />
<code><br />
$ mkdir cmake-build<br />
$ cd cmake-build<br />
$ ../bootstrap<br />
$ make<br />
$ make install<br />
</code><br />
<br />
Oletuksena yll&auml;oleva asentaa CMaken /usr/local, joten varmista ett&auml; /usr/local/bin on m&auml;&auml;ritelty polussa. Vaihtaaksesi asennushakemistoa (esim. /usr debianissa), lis&auml;&auml; '--prefix=PATH' valitsin bootstrap komentoon. (Esim: '''$ ../bootstrap --prefix=/usr''')<br />
<br />
Jos haluat asentaa viimeisimm&auml;n kehitysversion, seuraa ohjeita [http://cmake.org/HTML/Download.html#cvs t&auml;&auml;lt&auml;].<br />
<br />
==== Windows ====<br />
<br />
Hae viimeisin vakaa versio CMakesta [http://www.cmake.org/HTML/Download.html t&auml;&auml;lt&auml;.]<br />
<br />
Ladattuasi, suorita cmake asennusohjelma.<br />
<br />
Oletuksena CMake asennetaan C:\Program Files\CMake 2.4 - hakemistoon. Varmista ett&auml; C:\Program Files\CMake 2.4\bin l&ouml;ytyy polkumuuttujasta.<br />
<br />
Jos haluat asentaa viimeisimm&auml;n kehitysversion, seuraa ohjeita [http://cmake.org/HTML/Download.html#cvs t&auml;&auml;lt&auml;].<br />
<br />
=== CMaken k&auml;ytt&auml;minen ===<br />
==== Linux, BSD, sek&auml; muut Unix J&auml;rjestelm&auml;t ====<br />
<br />
Luodaksesi j&auml;rjestelm&auml;llesi k&auml;&auml;nn&ouml;stiedostot(Makefile) tarvitsee sinun ajaa CMake. Molemmat, l&auml;hdekoodin seassa sek&auml; l&auml;hdekoodin ulkopuolella k&auml;&auml;nn&ouml;kset, ovat CMaken puolelta tuettuja, mutta t&auml;ll&auml; hetkell&auml; l&auml;hdekoodin seassa k&auml;&auml;nt&auml;minen on estetty KDE:n toteutuksessa.<br />
<br />
Esikerkiksi, jos kdelibs/ sijaitsee ~/src hakemistossa niin k&auml;&auml;nt&auml;minen menee seuraavasti:<br />
<br />
<code><br />
$ ls<br />
kdelibs/<br />
$ mkdir kdelibs-build<br />
$ cd kdelibs-build<br />
$ cmake ../kdelibs<br />
</code><br />
<br />
Yll&auml;oleva tuottaa Makefilet kdelibs/ tiedostojen k&auml;&auml;nt&auml;miseksi kdelibs-build/ hakemistoon.<br />
<br />
==== Windows ====<br />
<br />
Luodaksesi j&auml;rjestelm&auml;llesi k&auml;&auml;nn&ouml;stiedostot(Makefile) tarvitsee sinun ajaa CMake. Molemmat, l&auml;hdekoodin seassa sek&auml; l&auml;hdekoodin ulkopuolella k&auml;&auml;nn&ouml;kset, ovat CMaken puolelta tuettuja, mutta t&auml;ll&auml; hetkell&auml; l&auml;hdekoodin seassa k&auml;&auml;nt&auml;minen on estetty KDE:n toteutuksessa.<br />
<br />
Esikerkiksi, jos kdelibs/ sijaitsee c:\data\kde4 hakemistossa niin k&auml;&auml;nt&auml;minen menee seuraavasti:<br />
<br />
<code><br />
c:\daten\kde4> cd kdelibs\win<br />
c:\daten\kde4> cmake<br />
c:\daten\kde4> make <br />
c:\daten\kde4> make install<br />
c:\daten\kde4> cd ..<br />
c:\daten\kde4> mkdir kdelibs-build<br />
c:\daten\kde4> cd kdelibs-build<br />
c:\daten\kde4\kdelibs-build> cmake ..\kdelibs<br />
</code><br />
<br />
Yll&auml;oleva tuottaa Makefilet kdelibs/ tiedostojen k&auml;&auml;nt&auml;miseksi kdelibs-build/ hakemistoon. Lis&auml;tietoja KDE:n k&auml;&auml;nt&auml;misest&auml; Windows ymp&auml;rist&ouml;ss&auml; l&ouml;ytyy [http://techbase.kde.org/index.php?title=Projects/KDE_on_Windows t&auml;&auml;lt&auml;].<br />
<br />
==== KDevelop Project Files ====<br />
<br />
Jos haluat luoda projektitiedostot KDevelopille(Makefile tiedostot sek&auml; muutamia Kdevelopin vaatimia lis&auml;tiedostoja), suorita CMake seuraavasti:<br />
<br />
<code><br />
$ cmake ../kdelibs -GKDevelop3<br />
</code><br />
<br />
'cmake -h' n&auml;ytt&auml;&auml; muut CMakessa tuetut valitsimet. <br />
<br />
==== CMake ja Qt4 ====<br />
<br />
Paikallistaakseen QT 4 kirjaston, CMake etsii qmakea polusta. CMake ei hy&ouml;dynn&auml; QTDIR ymp&auml;rist&ouml;muuttujaa, joten varmista ett&auml; oikea qmake l&ouml;ytyy ensimm&auml;isen&auml; polkumuuttujasta.<br />
<br />
<br />
==== Lis&auml;&auml; yksityiskohtia ====<br />
<br />
Kun CMaken suoritus on valmis, on CMake luonut tiedoston nimelt&auml; "CMakeCache.txt". T&auml;m&auml; tiedosto sis&auml;lt&auml;&auml; kaikki asetukset jotka CMake on tunnistanut j&auml;rjestelm&auml;st&auml;si. Jos haluat suorittaa CMaken tuottaaksesi k&auml;&auml;nn&ouml;stiedostot toiseen k&auml;&auml;nn&ouml;symp&auml;rist&ouml;&ouml;n, tai haluat ett&auml; asetukset tutkitaan uudelleen, poista t&auml;m&auml; tiedosto.<br />
<br />
Jos CMake ei l&ouml;yd&auml; jotain, mutta olet varma ett&auml; se on j&auml;rjestelm&auml;ss&auml;si, on mahdollista k&auml;sin kertoa CMakelle mist&auml; etsi&auml;. CMake k&auml;ytt&auml;&auml; apunaan muuttujia johon t&auml;m&auml; tieto tallennetaan. Muuttujat on varastoitu "CMakeCache.txt" tiedostoon. Muuttujien m&auml;&auml;rittelemiseksi k&auml;sin on kolme vaihtoehtoa:<br />
<br />
* Komentorivilt&auml;: '''cmake ../kdelibs -DMUUTTUJAN_NIMI=arvo'''<br />
* Merkkipohjainen ccmake k&auml;ytt&ouml;liittym&auml; (suorita: '''ccmake ../kdelibs''')<br />
* Muokkaamalla CMakeCache.txt tiedostoa (ei suositeltava) <br />
<br />
Kannattaa suorittaa "ccmake ../kdelibs" ainakin kerran jotta saat kokonaiskuvan kaikista niist&auml; muuttujista jota CMake k&auml;ytt&auml;&auml;. Ohjelmassa, paina "T", n&auml;hd&auml;ksesi my&ouml;s laajennetut muuttujat. Joten, jos CMake ei l&ouml;yd&auml; jotain, k&auml;ynnist&auml; ccmake ja aseta se k&auml;sin.<br />
<br />
==== Komentorivi Muuttujat ====<br />
<br />
Muutamia cmake:n komentorivill&auml; annettavia muuttujia joita saatat haluta muuttaa:<br />
<br />
* '''CMAKE_INSTALL_PREFIX:''' cmake ../kdelibs -DCMAKE_INSTALL_PREFIX=/opt/kde4 on vastaava ./configure --prefix=/opt/kde4<br />
* '''CMAKE_BUILD_TYPE:''' m&auml;&auml;rittelee k&auml;&auml;nn&ouml;styypin. Vaihtoehdot: "debugfull", "debug", "profile", "relwithdebinfo" ja "release". Oletuksena "relwithdebinfo" (-O2 -g). Katso lis&auml;tietoja: FindKDE4Internal.<br />
* '''KDE4_BUILD_TESTS=ON:''' Luo Makefilet testiohjelmien kanssa jotka my&ouml;s tuottavat testi k&auml;&auml;nn&ouml;kset<br />
* '''KDE4_TEST_OUTPUT=xml:''' Luo yksikk&ouml;testeist&auml; xml muotoiset lokitiedostot QTestLib:&auml; k&auml;ytt&auml;en.<br />
* '''KDE4_DISABLE_MULTIMEDIA=ON:''' K&auml;&auml;nt&auml;&auml; KDE:n ilman multimedia(&auml;&auml;ni ja video) tukea.<br />
* '''RPATH_STYLE:''' Ei en&auml;&auml;n valittavissa. Oletuksena kaikki k&auml;&auml;nnet&auml;&auml;n oikein asetetun RPATH:n kanssa. Jos et halua k&auml;ytt&auml;&auml; lainkaan RPATH:a, aseta '''CMAKE_SKIP_RPATH=TRUE'''.<br />
* '''BUILD_foo=OFF:''' J&auml;tt&auml;&auml; 'foo' hakemiston k&auml;&auml;nt&auml;m&auml;tt&auml;.<br />
* '''WITH_foo:''' T&auml;h&auml;n on useita vaihtoehtoja, esim: WITH_CUPS tai WITH_Jasper. Jos poissuljet(=OFF), cmake ei edes yrit&auml; etsi&auml; n&auml;it&auml;. Jos on valittu, cmake yritt&auml;&auml; etsi&auml; n&auml;it&auml;. Jos haku ep&auml;onnistuu, voit silti m&auml;&auml;ritell&auml; sijainnin k&auml;sin kute aikaisemmin neuvottiin.<br />
<br />
==== Ymp&auml;rist&ouml;muuttujat ====<br />
<br />
Jos sinulla on otsikkotiedostoja tai kirjastoja asennettuna ep&auml;tavallisiin hakemistoihin, joista cmake ei niit&auml; l&ouml;yd&auml;, pit&auml;&auml; asettaa seuraavat ymp&auml;rist&ouml;muuttujat. Huolimatta samankaltaisesta nime&auml;mistyylist&auml;, n&auml;it&auml; ei voi antaa cmakelle komentorivilt&auml;.<br />
<br />
* '''CMAKE_INCLUDE_PATH''', eg. export CMAKE_INCLUDE_PATH=/sw/include<br />
* '''CMAKE_LIBRARY_PATH''', eg. export CMAKE_LIBRARY_PATH=/sw/lib <br />
<br />
Lis&auml;tietoja muuttujista, katso [http://www.cmake.org/Wiki/CMake_Useful_Variables cmake.org wiki sivu].<br />
<br />
==== Seuraavaksi ====<br />
<br />
Jos cmake:n suoritus p&auml;&auml;ttyy ilmoitukseen "Generating done", ei virheit&auml; ilmentynyt. Nyt voit suorittaa k&auml;&auml;nn&ouml;ksen normaaliin tapaan(make, KDevelop, XCode tai MSVC). K&auml;&auml;nn&ouml;ksen j&auml;lkeen asennus normaalisti esim "make install"<br />
<br />
Jos suoritus p&auml;&auml;ttyy ilmoitukseen "Configuring done", on ilmennyt joitain virheit&auml; jotka pit&auml;&auml; selvitt&auml;&auml;. <br />
<br />
Jos sait virheilmoituksen jossa kerrotaan jotain seuraavaa<br />
<code><br />
CMake Error: This project requires some variables to be set,<br />
and cmake can not find them.<br />
Please set the following variables:<br />
X11_XTest_LIB (ADVANCED)<br />
</code><br />
<br />
, niin luultavammin jokin kirjastoa (tai muuta riippuvuutta) ei l&ouml;ytynyt. Selvitt&auml;&auml;ksesi mik&auml; kirjasto on kyseess&auml;, etsi cmake/modules hakemistosta muuttujaa jota cmake ei l&ouml;y&auml;nyt. T&auml;ss&auml; esimerkiss&auml; se on<br />
<br />
<code><br />
FIND_LIBRARY(X11_XTest_LIB Xtst ${X11_LIB_SEARCH_PATH})<br />
</code><br />
<br />
Joten puuttuva tai ep&auml;normaaliin sijaintiin asennettu kirjasto on Xtst. Kirjaston asentamisen j&auml;lkeen suorita uudelleen cmake. <br />
<br />
== CMaken k&auml;ytt&ouml; yksinkertaisessa sovelluksessa ==<br />
<br />
Yksinkertsin toimiva CMakeLists.txt:<br />
<br />
<code><br />
add_executable(hello main.cpp)<br />
</code><br />
<br />
T&auml;m&auml; tuottaa main.cpp l&auml;hdekooditiedostosta suoritettavan ohjelman nimelt&auml; "hello" (tai "hello.exe" Windowsissa). Voit k&auml;ytt&auml;&auml; samanaikaisesti sek&auml; C att&auml; C++ tiedostoja. Voit sijoittaa useampia suoritettavia bin&auml;&auml;rej&auml; tai kirjastoja samaan CMakeLists.txt tiedostoon. Samaa l&auml;hdekooditiedostoa voidaan k&auml;ytt&auml;&auml; useamman bin&auml;&auml;rin k&auml;&auml;nt&auml;miseen ja se k&auml;&auml;nnet&auml;&auml;n jokaista bin&auml;&auml;ri&auml; kohden erikseen riippumatta muista bin&auml;&auml;reist&auml;. Luultavammin t&auml;rkein osa cmaken komentokieless&auml; ovat muuttujat:<br />
<br />
<code><br />
SET( MY_SOURCES main.cpp widget.cpp)<br />
MESSAGE(STATUS "my sources: ${MY_SOURCES}")<br />
</code><br />
<br />
SET() komennolla voit asettaa muuttujalle arvon. Jos asetat arvoksi useamman merkkijonon, muutujan tyypiksi tulee lista. Lista on puolipisteill&auml; eroteltu merkkijonojen luettelo. Saadaksesi muuttujan arvon k&auml;yt&auml; $(MUUTTUJA). Listan voit iteroida seuraavasti:<br />
<code><br />
FOREACH():<br />
<br />
FOREACH(next_ITEM ${MY_SOURCES})<br />
MESSAGE(STATUS "next item: ${next_ITEM}")<br />
ENDFOREACH(next_ITEM ${MY_SOURCES})<br />
</code><br />
<br />
CMaken komennoissa, muuttujien nimiss&auml; ja muuttujien parametreiss&auml; on huomioitava kirjainkoko. (a != A)<br />
<br />
Voit my&ouml;s testata asioita:<br />
<br />
<code><br />
IF (UNIX)<br />
MESSAGE(STATUS "This is UNIX (including OS X and CygWin)")<br />
ENDIF (UNIX)<br />
<br />
IF (MSVC)<br />
SET(MY_SRCS ${MY_SRCS} winextra.cpp)<br />
ENDIF (MSVC)<br />
</code><br />
<br />
J&auml;lkimm&auml;isess&auml; esimerkiss&auml; n&auml;ytet&auml;&auml;n my&ouml;s miten lis&auml;t&auml; listaan merkkijono.<br />
<br />
Suositeltavana lukemisena on cmake Wikiss&auml; perehdytys "[http://www.cmake.org/Wiki/HowToBuildKDE4Software Kuinka k&auml;&auml;nn&auml;n KDE 4 ohjelmistoja]".<br />
<br />
<br />
== CMaken k&auml;ytt&ouml; KDE Projektissa ==<br />
<br />
Seuraavana on perus CMakeList tiedosto jonlla voi k&auml;&auml;nt&auml;&auml; KDE 4 projektin:<br />
<br />
<code><br />
PROJECT(kde4project)<br />
FIND_PACKAGE(KDE4 REQUIRED)<br />
INCLUDE_DIRECTORIES( ${KDE4_INCLUDES} )<br />
<br />
SET(KDE4ProjectSources kde4mainapp.cpp someclass.cpp someotherclass.cpp)<br />
<br />
KDE4_ADD_EXECUTABLE(kde4project ${KDE4ProjectSources} )<br />
<br />
TARGET_LINK_LIBRARIES(kde4project ${KDE4_KDEUI_LIBS} ${KDE4_KPARTS_LIBS} )<br />
</code><br />
<br />
Muuttujat, makrot ja muuta KDE:&auml; koskevaa hy&ouml;dyllist&auml; tietoa l&ouml;ytyy [[Development/KDE and CMake Together]] - sivulta.<br />
<br />
== CMaken Laajentaminen ==<br />
<br />
CMakea voi laajentaa k&auml;ytt&auml;m&auml;ll&auml; cmake komentojonoja. CMaken mukana tulee useita valmiita komentojonoja. UNIX pohjaisissa j&auml;rjestelmiss&auml; ne on asennettuna oletuksena /usr/local/share/CMake/Modules hakemistoon(riippuen CMaken asennushakemistosta). KDE kirjastot asentavat my&ouml;s joukon cmake laajennuksia share/apps/cmake/modules/ hakemistoon. KDE:n hakemistossa sijaitsevat laajennukset ohittavat j&auml;rjestelm&auml;nlaajuiset cmaken laajennukset. Ohjelmapakettien etsimist&auml; varten t&auml;&auml;ll&auml; on FindFOO.cmake tiedostot, katso lis&auml;tietoja [http://www.cmake.org/Wiki/CMake_HowToFindInstalledSoftware t&auml;&auml;lt&auml;]. CMaken kanssa on my&ouml;s mahdollista k&auml;ytt&auml;&auml; makroja, jotka ovat k&auml;ytt&ouml;kelpoisia useimpiin tilanteisiin joita ohjemien k&auml;&auml;nt&auml;misess&auml; tarvitaan.<br />
<br />
== autotools-pohjaisen KDE ohjelmiston k&auml;&auml;nt&auml;minen CMakelle ==<br />
<br />
Hakemistossa kdesdk/cmake/ on tiedosto nimelt&auml;&auml;n am2cmake. am2cmakea on ruby tiedosto, joten ruby tulee olla asennettu. Suorita am2cmake l&auml;hdekoodin p&auml;&auml;hakemistossa:<br />
<br />
<code><br />
$ cd src/mykooltool/<br />
$ am2cmake --kde4<br />
</code><br />
<br />
&Auml;l&auml; unohda "--kde4" - valitsinta, muuten am2cmake ei tuota KDE 4 ohjelmistoille sopivia tiedostoja. K&auml;&auml;nnetyt tiedostot 'voivat' toimia sellaisenaan k&auml;&auml;nt&auml;misen j&auml;lkeen, mutta monimutkaisemmat projektit yleens&auml; vaativat lis&auml;muokkauksia.<br />
<br />
Saatat joutua:<br />
<br />
* lis&auml;&auml;m&auml;&auml;n sis&auml;llytett&auml;via hakemistoja, k&auml;ytt&auml;en INCLUDE_DIRECTORIES()<br />
* lis&auml;&auml;m&auml;&auml;n linkkej&auml; kirjastoihin, k&auml;ytt&auml;en TARGET_LINK_LIBRARIES()<br />
* lis&auml;&auml;m&auml;&auml;n joitain m&auml;&auml;rittelyj&auml; k&auml;&auml;nt&auml;j&auml;lle, k&auml;ytt&auml;en ADD_DEFINITIONS()<br />
* lis&auml;&auml;m&auml;&auml;n tarkistuksia. Katso [[http://www.cmake.org/Wiki/CMake_HowToDoPlatformChecks Kuinka Tehd&auml; Ymp&auml;rist&ouml; Tarkistuksia] sek&auml; [http://www.cmake.org/Wiki/CMake_HowToFindInstalledSoftware Kuinka L&ouml;yt&auml;&auml; Asennettuja Ohjelmia]<br />
* huolehtimaan libtool-yhteensopivista kirjastoista. Ne eiv&auml;t ole tuettuina cmakessa, sen sijaan on ConvenienceLibs.cmake. T&auml;st&auml; tiedostosta l&ouml;yd&auml;t jokaiselle yhteensopivuus kirjastolle muuttujan, joka sis&auml;lt&auml;&auml; kaikki kyseisen yhteensopivuustiedoston l&auml;hteet.<br />
* am2cmake luo tiedoston nimelt&auml; AdditionalInfo.txt. T&auml;ss&auml; tiedostossa on lueteltu kaikki *.in ja *.in.in tiedostot kyseisest&auml; projektista. N&auml;iss&auml; tiedostoissa olevat asiat pit&auml;&auml; k&auml;&auml;nt&auml;&auml; k&auml;sin CMakelle.<br />
<br />
<br />
== Usein Kysyttyj&auml; Kysymyksi&auml; ==<br />
<br />
=== Kuinka voin opettaa k&auml;ytt&auml;m&auml;lleni tekstieditorille CMaken syntaksin ja sisennykset ? ===<br />
Katso CMake Winkin osiossa [http://www.cmake.org/Wiki/CMake_Editors_Support CMake Editors Support] on ohjeet Emacs (my&ouml;s XEmacs), VIM, Kate, KWrite, sek&auml; KDevelop editoreille.<br />
<br />
=== K&auml;&auml;nn&ouml;ksen aikana pit&auml;isi luoda er&auml;it&auml; tiedostoja. Kuinka ne tehd&auml;&auml;n ? ===<br />
K&auml;yt&auml;: ADD_CUSTOM_COMMAND(). Sen toiminta on selitetty CMake wikiss&auml;: [http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_generate_a_source_file_during_the_build.3F Kuinka luon l&auml;hdetiedoston k&auml;&auml;nn&ouml;n aikana]<br />
<br />
=== Minun pit&auml;isi k&auml;&auml;nt&auml;&auml; ohjelma jota k&auml;ytet&auml;&auml;n my&ouml;hemmin k&auml;&auml;nn&ouml;sty&ouml;ss&auml; luomaan tiedostoja. Kuinka t&auml;m&auml; tehd&auml;&auml;n ? ===<br />
Ajatellaan ett&auml; luotavan ohjelman nimi on genembed. K&auml;yt&auml; KDE4_ADD_EXECUTABLE(foo RUN_UNINSTALLED ${fooSources})luodaksesi k&auml;ynnistett&auml;v&auml; bin&auml;&auml;ri. RUN_UNINSTALLED on t&auml;rke&auml;, koska ohjelmaa ajetaan k&auml;&auml;nn&ouml;shakemistossa ja se pit&auml;&auml; linkitt&auml;&auml; k&auml;&auml;nn&ouml;shakemiston kirjastoihin. Suoritettava bin&auml;&auml;ri(ohjelma) on k&auml;&auml;nnetty RPATH asetusten mukaisesti ja on luotu suoritettava shellin komentojonotiedosto, samanniminen kuin ohjelma, mutta p&auml;&auml;tteell&auml; ".sh". Shellin komentojonotiedosto asettaa LD_LIBRARY_PATH muuttujan ja suorittaa varsinaisen ohjelman.<br />
K&auml;yt&auml; t&auml;t&auml; komentojonotiedostoa komennolla ADD_CUSTOM_COMMAND() kuten alla olevassa esimerkiss&auml;. Nimen ja tarkan sijainnin saat WRAPPER_SCRIPT muuttujasta.<br />
Esimerkki, kdelibs/kstyles/keramik/:a kopioitu esimerkki:<br />
<code><br />
# k&auml;&auml;nn&auml; ajettava bin&auml;&auml;ri<br />
KDE4_ADD_EXECUTABLE(genembed RUN_UNINSTALLED ${genembed_SRCS})<br />
<br />
# hae komentojonotiedoston nimi(joka asettaa LD_LIBRARY_PATH muuttujan)<br />
GET_TARGET_PROPERTY(GENEMBED_EXECUTABLE genembed WRAPPER_SCRIPT)<br />
<br />
# ja viimein oma komento<br />
ADD_CUSTOM_COMMAND(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/keramikrc.h<br />
COMMAND ${GENEMBED_EXECUTABLE} --file ${CMAKE_CURRENT_BINARY_DIR}/keramikPics.txt > \<br />
${CMAKE_CURRENT_BINARY_DIR}/pixmaps.keramik<br />
DEPENDS genembed ${keramikPics}<br />
)<br />
</code><br />
<br />
Kuten huomaat genembed on my&ouml;s listattu riippuvuudeksi, joka tarkoittaa ett&auml; cmake tiet&auml;&auml; ett&auml; sen on luotava bin&auml;&auml;ri nimelt&auml; genembed ennenkuin se voi suorittaa kyseisen oman komennon.<br />
<br />
=== En haluaisi k&auml;ytt&auml;&auml; -DCMAKE_INSTALL_PREFIX komentoriviparametri&auml;. Onko KDEDIR ymp&auml;rist&ouml;muuttuja tuettu CMakessa ? ===<br />
Ei. $KDEDIR on j&auml;&auml;m&auml;ss&auml; pois KDE 4:ss&auml;.<br />
<br />
=== Miksi saan k&auml;&auml;nt&auml;j&auml;virheit&auml; kuten /usr/lib/qt4/include/QtCore/qstring.h:536: undefined reference to `QString::fromLatin1_helper(char const*, int)'? ===<br />
Jos sinulla on vanha Qt4 versio qt/lib hakemistossa, sinun pit&auml;&auml; poistaa vanhat (4.0.1) tiedostot.<br />
<br />
=== Kuinka saan tehty&auml; &auml;&auml;nekk&auml;it&auml; Makefile tiedostoja? Haluan seurata tarkasti mik&auml; komento milloinkin on menossa. ===<br />
Anna VERBOSE muuttuja make:lle, esim:<br />
<code><br />
% make VERBOSE=1<br />
</code><br />
or<br />
<code><br />
% VERBOSE=1 make<br />
</code><br />
<br />
Lis&auml;tietoja, katso CMake wiki: [http://www.cmake.org/Wiki/CMake_FAQ#Is_there_an_option_to_produce_more_.27verbose.27_compiling.3F Is there an option to produce more 'verbose' compiling?]<br />
<br />
=== Makefiless&auml; ei ole 'make distclean' kohdetta. Kuinka siivoan pois kaikki, my&ouml;s v&auml;limuistissa olevat tiedostot ? ===<br />
Yksinkertaisesti, poista k&auml;&auml;nn&ouml;shakemisto, tai k&auml;&auml;nn&ouml;shakemiston sis&auml;lt&ouml;.<br />
<br />
[[Category:Programming]]<br />
[[Category:Tutorial]]<br />
[[Category:FAQs]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/CMake_(fi)&diff=19477Development/Tutorials/CMake (fi)2008-01-10T19:43:25Z<p>Ozzi: Skandit kuntoon</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/CMake}}<br />
<br />
== Esipuhe ==<br />
<br />
CMake tuottaa ohjaustiedostot j&auml;rjestelm&auml;n omalle k&auml;&auml;nt&auml;j&auml;lle omien komentotiedostojensa avulla. Se voi luoda GNU Makefilet, KDevelop-projektitiedostot, XCode-projektitiedostot, sek&auml; Visual Studio-projektitiedostot.<br />
<br />
CMake on vapaan l&auml;hdekoodin ohjelmisto joka on julkaistu BSD-tyylisen lisenssin alaisena. CMaken yll&auml;pit&auml;j&auml; on [http://www.kitware.com/ Kitware Inc.]<br />
<br />
N&auml;ist&auml; voit aloittaa CMaken perusteiden opiskelun (englanniksi):<br />
* [http://www.cmake.org/HTML/Documentation.html CMake Ohjekirja]<br />
* [http://www.cmake.org/Wiki/CMake CMake Wiki]<br />
* [http://www.cmake.org/Wiki/CMake_HowToDoPlatformChecks CMake - J&auml;rjestelm&auml;n Tarkistukset]<br />
* [http://www.cmake.org/Wiki/CMake_HowToFindInstalledSoftware CMake - Kuinka L&ouml;yt&auml;&auml; Asennetut Ohjelmat]<br />
* [http://www.cmake.org/Wiki/HowToBuildKDE4Software KDE 4 Perehdytys CMake Wikiss&auml;]<br />
* [http://www.cmake.org/Wiki/CMake_FAQ CMake FAQ]<br />
* [http://mail.kde.org/pipermail/kde-buildsystem/ Kde-buildsystem - Postituslistan arkisto]<br />
Voit my&ouml;s liitty&auml; CMake [http://www.cmake.org/mailman/listinfo/cmake postituslistalle].<br />
<br />
== Miksi k&auml;ytt&auml;&auml; CMakea ? ==<br />
<br />
Maaliskuussa 2006 p&auml;&auml;tettiin valita CMake KDE 4 julkaisun viralliseksi ty&ouml;kaluksi, p&auml;&auml;s&auml;&auml;nt&ouml;isesti sen teknisten ominaisuuksien vuoksi verrattuna vankempiin KDE ty&ouml;kaluihin kuten automake ja unsermake:<br />
<br />
* CMake on kehitetty KDE:st&auml; riippumattomana, ja sit&auml; voidaan k&auml;ytt&auml;&auml; my&ouml;s muissa projekteissa<br />
* K&auml;&auml;nn&ouml;sajat j&auml;&auml;v&auml;t paljon pienemmiksi, p&auml;&auml;osin koska libtoolia ei en&auml;&auml; tarvita<br />
* K&auml;&auml;nn&ouml;stiedostot ovat helpompia kirjoittaa<br />
<br />
== KDE:n k&auml;&auml;nt&auml;minen CMakea k&auml;ytt&auml;en ==<br />
=== Lataa ja asenna CMake ===<br />
==== Linux, BSD, sek&auml; muut Unix J&auml;rjestelm&auml;t ====<br />
Hae viimeisin vakaa versio CMakesta [http://www.cmake.org/HTML/Download.html t&auml;&auml;lt&auml;.]<br />
<br />
Pura ja k&auml;&auml;nn&auml;:<br />
<br />
<code><br />
$ mkdir cmake-build<br />
$ cd cmake-build<br />
$ ../bootstrap<br />
$ make<br />
$ make install<br />
</code><br />
<br />
Oletuksena yll&auml;oleva asentaa CMaken /usr/local, joten varmista ett&auml; /usr/local/bin on m&auml;&auml;ritelty polussa. Vaihtaaksesi asennushakemistoa (esim. /usr debianissa), lis&auml;&auml; '--prefix=PATH' valitsin bootstrap komentoon. (Esim: '''$ ../bootstrap --prefix=/usr''')<br />
<br />
Jos haluat asentaa viimeisimm&auml;n kehitysversion, seuraa ohjeita [http://cmake.org/HTML/Download.html#cvs t&auml;&auml;lt&auml;].<br />
<br />
==== Windows ====<br />
<br />
Hae viimeisin vakaa versio CMakesta [http://www.cmake.org/HTML/Download.html t&auml;&auml;lt&auml;.]<br />
<br />
Ladattuasi, suorita cmake asennusohjelma.<br />
<br />
Oletuksena CMake asennetaan C:\Program Files\CMake 2.4 - hakemistoon. Varmista ett&auml; C:\Program Files\CMake 2.4\bin l&ouml;ytyy polkumuuttujasta.<br />
<br />
Jos haluat asentaa viimeisimm&auml;n kehitysversion, seuraa ohjeita [http://cmake.org/HTML/Download.html#cvs t&auml;&auml;lt&auml;].<br />
<br />
=== CMaken k&auml;ytt&auml;minen ===<br />
==== Linux, BSD, sek&auml; muut Unix J&auml;rjestelm&auml;t ====<br />
<br />
Luodaksesi j&auml;rjestelm&auml;llesi k&auml;&auml;nn&ouml;stiedostot(Makefile) tarvitsee sinun ajaa CMake. Molemmat, l&auml;hdekoodin seassa sek&auml; l&auml;hdekoodin ulkopuolella k&auml;&auml;nn&ouml;kset, ovat CMaken puolelta tuettuja, mutta t&auml;ll&auml; hetkell&auml; l&auml;hdekoodin seassa k&auml;&auml;nt&auml;minen on estetty KDE:n toteutuksessa.<br />
<br />
Esikerkiksi, jos kdelibs/ sijaitsee ~/src hakemistossa niin k&auml;&auml;nt&auml;minen menee seuraavasti:<br />
<br />
<code><br />
$ ls<br />
kdelibs/<br />
$ mkdir kdelibs-build<br />
$ cd kdelibs-build<br />
$ cmake ../kdelibs<br />
</code><br />
<br />
Yll&auml;oleva tuottaa Makefilet kdelibs/ tiedostojen k&auml;&auml;nt&auml;miseksi kdelibs-build/ hakemistoon.<br />
<br />
==== Windows ====<br />
<br />
Luodaksesi j&auml;rjestelm&auml;llesi k&auml;&auml;nn&ouml;stiedostot(Makefile) tarvitsee sinun ajaa CMake. Molemmat, l&auml;hdekoodin seassa sek&auml; l&auml;hdekoodin ulkopuolella k&auml;&auml;nn&ouml;kset, ovat CMaken puolelta tuettuja, mutta t&auml;ll&auml; hetkell&auml; l&auml;hdekoodin seassa k&auml;&auml;nt&auml;minen on estetty KDE:n toteutuksessa.<br />
<br />
Esikerkiksi, jos kdelibs/ sijaitsee c:\data\kde4 hakemistossa niin k&auml;&auml;nt&auml;minen menee seuraavasti:<br />
<br />
<code><br />
c:\daten\kde4> cd kdelibs\win<br />
c:\daten\kde4> cmake<br />
c:\daten\kde4> make <br />
c:\daten\kde4> make install<br />
c:\daten\kde4> cd ..<br />
c:\daten\kde4> mkdir kdelibs-build<br />
c:\daten\kde4> cd kdelibs-build<br />
c:\daten\kde4\kdelibs-build> cmake ..\kdelibs<br />
</code><br />
<br />
Yll&auml;oleva tuottaa Makefilet kdelibs/ tiedostojen k&auml;&auml;nt&auml;miseksi kdelibs-build/ hakemistoon. Lis&auml;tietoja KDE:n k&auml;&auml;nt&auml;misest&auml; Windows ymp&auml;rist&ouml;ss&auml; l&ouml;ytyy [http://techbase.kde.org/index.php?title=Projects/KDE_on_Windows t&auml;&auml;lt&auml;].<br />
<br />
==== KDevelop Project Files ====<br />
<br />
Jos haluat luoda projektitiedostot KDevelopille(Makefile tiedostot sek&auml; muutamia Kdevelopin vaatimia lis&auml;tiedostoja), suorita CMake seuraavasti:<br />
<br />
<code><br />
$ cmake ../kdelibs -GKDevelop3<br />
</code><br />
<br />
'cmake -h' n&auml;ytt&auml;&auml; muut CMakessa tuetut valitsimet. <br />
<br />
==== CMake ja Qt4 ====<br />
<br />
Paikallistaakseen QT 4 kirjaston, CMake etsii qmakea polusta. CMake ei hy&ouml;dynn&auml; QTDIR ymp&auml;rist&ouml;muuttujaa, joten varmista ett&auml; oikea qmake l&ouml;ytyy ensimm&auml;isen&auml; polkumuuttujasta.<br />
<br />
<br />
==== Lis&auml;&auml; yksityiskohtia ====<br />
<br />
Kun CMaken suoritus on valmis, on CMake luonut tiedoston nimelt&auml; "CMakeCache.txt". T&auml;m&auml; tiedosto sis&auml;lt&auml;&auml; kaikki asetukset jotka CMake on tunnistanut j&auml;rjestelm&auml;st&auml;si. Jos haluat suorittaa CMaken tuottaaksesi k&auml;&auml;nn&ouml;stiedostot toiseen k&auml;&auml;nn&ouml;symp&auml;rist&ouml;&ouml;n, tai haluat ett&auml; asetukset tutkitaan uudelleen, poista t&auml;m&auml; tiedosto.<br />
<br />
Jos CMake ei l&ouml;yd&auml; jotain, mutta olet varma ett&auml; se on j&auml;rjestelm&auml;ss&auml;si, on mahdollista k&auml;sin kertoa CMakelle mist&auml; etsi&auml;. CMake k&auml;ytt&auml;&auml; apunaan muuttujia johon t&auml;m&auml; tieto tallennetaan. Muuttujat on varastoitu "CMakeCache.txt" tiedostoon. Muuttujien m&auml;&auml;rittelemiseksi k&auml;sin on kolme vaihtoehtoa:<br />
<br />
* Komentorivilt&auml;: '''cmake ../kdelibs -DMUUTTUJAN_NIMI=arvo'''<br />
* Merkkipohjainen ccmake k&auml;ytt&ouml;liittym&auml; (suorita: '''ccmake ../kdelibs''')<br />
* Muokkaamalla CMakeCache.txt tiedostoa (ei suositeltava) <br />
<br />
Kannattaa suorittaa "ccmake ../kdelibs" ainakin kerran jotta saat kokonaiskuvan kaikista niist&auml; muuttujista jota CMake k&auml;ytt&auml;&auml;. Ohjelmassa, paina "T", n&auml;hd&auml;ksesi my&ouml;s laajennetut muuttujat. Joten, jos CMake ei l&ouml;yd&auml; jotain, k&auml;ynnist&auml; ccmake ja aseta se k&auml;sin.<br />
<br />
==== Komentorivi Muuttujat ====<br />
<br />
Muutamia cmake:n komentorivill&auml; annettavia muuttujia joita saatat haluta muuttaa:<br />
<br />
* '''CMAKE_INSTALL_PREFIX:''' cmake ../kdelibs -DCMAKE_INSTALL_PREFIX=/opt/kde4 on vastaava ./configure --prefix=/opt/kde4<br />
* '''CMAKE_BUILD_TYPE:''' m&auml;&auml;rittelee k&auml;&auml;nn&ouml;styypin. Vaihtoehdot: "debugfull", "debug", "profile", "relwithdebinfo" ja "release". Oletuksena "relwithdebinfo" (-O2 -g). Katso lis&auml;tietoja: FindKDE4Internal.<br />
* '''KDE4_BUILD_TESTS=ON:''' Luo Makefilet testiohjelmien kanssa jotka my&ouml;s tuottavat testi k&auml;&auml;nn&ouml;kset<br />
* '''KDE4_TEST_OUTPUT=xml:''' Luo yksikk&ouml;testeist&auml; xml muotoiset lokitiedostot QTestLib:&auml; k&auml;ytt&auml;en.<br />
* '''KDE4_DISABLE_MULTIMEDIA=ON:''' K&auml;&auml;nt&auml;&auml; KDE:n ilman multimedia(&auml;&auml;ni ja video) tukea.<br />
* '''RPATH_STYLE:''' Ei en&auml;&auml;n valittavissa. Oletuksena kaikki k&auml;&auml;nnet&auml;&auml;n oikein asetetun RPATH:n kanssa. Jos et halua k&auml;ytt&auml;&auml; lainkaan RPATH:a, aseta '''CMAKE_SKIP_RPATH=TRUE'''.<br />
* '''BUILD_foo=OFF:''' J&auml;tt&auml;&auml; 'foo' hakemiston k&auml;&auml;nt&auml;m&auml;tt&auml;.<br />
* '''WITH_foo:''' T&auml;h&auml;n on useita vaihtoehtoja, esim: WITH_CUPS tai WITH_Jasper. Jos poissuljet(=OFF), cmake ei edes yrit&auml; etsi&auml; n&auml;it&auml;. Jos on valittu, cmake yritt&auml;&auml; etsi&auml; n&auml;it&auml;. Jos haku ep&auml;onnistuu, voit silti m&auml;&auml;ritell&auml; sijainnin k&auml;sin kute aikaisemmin neuvottiin.<br />
<br />
==== Ymp&auml;rist&ouml;muuttujat ====<br />
<br />
Jos sinulla on otsikkotiedostoja tai kirjastoja asennettuna ep&auml;tavallisiin hakemistoihin, joista cmake ei niit&auml; l&ouml;yd&auml;, pit&auml;&auml; asettaa seuraavat ymp&auml;rist&ouml;muuttujat. Huolimatta samankaltaisesta nime&auml;mistyylist&auml;, n&auml;it&auml; ei voi antaa cmakelle komentorivilt&auml;.<br />
<br />
* '''CMAKE_INCLUDE_PATH''', eg. export CMAKE_INCLUDE_PATH=/sw/include<br />
* '''CMAKE_LIBRARY_PATH''', eg. export CMAKE_LIBRARY_PATH=/sw/lib <br />
<br />
Lis&auml;tietoja muuttujista, katso [http://www.cmake.org/Wiki/CMake_Useful_Variables cmake.org wiki sivu].<br />
<br />
==== Seuraavaksi ====<br />
<br />
Jos cmake:n suoritus p&auml;&auml;ttyy ilmoitukseen "Generating done", ei virheit&auml; ilmentynyt. Nyt voit suorittaa k&auml;&auml;nn&ouml;ksen normaaliin tapaan(make, KDevelop, XCode tai MSVC). K&auml;&auml;nn&ouml;ksen j&auml;lkeen asennus normaalisti esim "make install"<br />
<br />
Jos suoritus p&auml;&auml;ttyy ilmoitukseen "Configuring done", on ilmennyt joitain virheit&auml; jotka pit&auml;&auml; selvitt&auml;&auml;. <br />
<br />
Jos sait virheilmoituksen jossa kerrotaan jotain seuraavaa<br />
<code><br />
CMake Error: This project requires some variables to be set,<br />
and cmake can not find them.<br />
Please set the following variables:<br />
X11_XTest_LIB (ADVANCED)<br />
</code><br />
<br />
, niin luultavammin jokin kirjastoa (tai muuta riippuvuutta) ei l&ouml;ytynyt. Selvitt&auml;&auml;ksesi mik&auml; kirjasto on kyseess&auml;, etsi cmake/modules hakemistosta muuttujaa jota cmake ei l&ouml;y&auml;nyt. T&auml;ss&auml; esimerkiss&auml; se on<br />
<br />
<code><br />
FIND_LIBRARY(X11_XTest_LIB Xtst ${X11_LIB_SEARCH_PATH})<br />
</code><br />
<br />
Joten puuttuva tai ep&auml;normaaliin sijaintiin asennettu kirjasto on Xtst. Kirjaston asentamisen j&auml;lkeen suorita uudelleen cmake. <br />
<br />
== CMaken k&auml;ytt&ouml; yksinkertaisessa sovelluksessa ==<br />
<br />
Yksinkertsin toimiva CMakeLists.txt:<br />
<br />
<code><br />
add_executable(hello main.cpp)<br />
</code><br />
<br />
T&auml;m&auml; tuottaa main.cpp l&auml;hdekooditiedostosta suoritettavan ohjelman nimelt&auml; "hello" (tai "hello.exe" Windowsissa). Voit k&auml;ytt&auml;&auml; samanaikaisesti sek&auml; C att&auml; C++ tiedostoja. Voit sijoittaa useampia suoritettavia bin&auml;&auml;rej&auml; tai kirjastoja samaan CMakeLists.txt tiedostoon. Samaa l&auml;hdekooditiedostoa voidaan k&auml;ytt&auml;&auml; useamman bin&auml;&auml;rin k&auml;&auml;nt&auml;miseen ja se k&auml;&auml;nnet&auml;&auml;n jokaista bin&auml;&auml;ri&auml; kohden erikseen riippumatta muista bin&auml;&auml;reist&auml;. Luultavammin t&auml;rkein osa cmaken komentokieless&auml; ovat muuttujat:<br />
<br />
<code><br />
SET( MY_SOURCES main.cpp widget.cpp)<br />
MESSAGE(STATUS "my sources: ${MY_SOURCES}")<br />
</code><br />
<br />
SET() komennolla voit asettaa muuttujalle arvon. Jos asetat arvoksi useamman merkkijonon, muutujan tyypiksi tulee lista. Lista on puolipisteill&auml; eroteltu merkkijonojen luettelo. Saadaksesi muuttujan arvon k&auml;yt&auml; $(MUUTTUJA). Listan voit iteroida seuraavasti:<br />
<code><br />
FOREACH():<br />
<br />
FOREACH(next_ITEM ${MY_SOURCES})<br />
MESSAGE(STATUS "next item: ${next_ITEM}")<br />
ENDFOREACH(next_ITEM ${MY_SOURCES})<br />
</code><br />
<br />
CMaken komennoissa, muuttujien nimiss&auml; ja muuttujien parametreiss&auml; on huomioitava kirjainkoko. (a != A)<br />
<br />
Voit my&ouml;s testata asioita:<br />
<br />
<code><br />
IF (UNIX)<br />
MESSAGE(STATUS "This is UNIX (including OS X and CygWin)")<br />
ENDIF (UNIX)<br />
<br />
IF (MSVC)<br />
SET(MY_SRCS ${MY_SRCS} winextra.cpp)<br />
ENDIF (MSVC)<br />
</code><br />
<br />
J&auml;lkimm&auml;isess&auml; esimerkiss&auml; n&auml;ytet&auml;&auml;n my&ouml;s miten lis&auml;t&auml; listaan merkkijono.<br />
<br />
Suositeltavana lukemisena on cmake Wikiss&auml; perehdytys "[http://www.cmake.org/Wiki/HowToBuildKDE4Software Kuinka k&auml;&auml;nn&auml;n KDE 4 ohjelmistoja]".<br />
<br />
<br />
== CMaken k&auml;ytt&ouml; KDE Projektissa ==<br />
<br />
Seuraavana on perus CMakeList tiedosto jonlla voi k&auml;&auml;nt&auml;&auml; KDE 4 projektin:<br />
<br />
<code><br />
PROJECT(kde4project)<br />
FIND_PACKAGE(KDE4 REQUIRED)<br />
INCLUDE_DIRECTORIES( ${KDE4_INCLUDES} )<br />
<br />
SET(KDE4ProjectSources kde4mainapp.cpp someclass.cpp someotherclass.cpp)<br />
<br />
KDE4_ADD_EXECUTABLE(kde4project ${KDE4ProjectSources} )<br />
<br />
TARGET_LINK_LIBRARIES(kde4project ${KDE4_KDEUI_LIBS} ${KDE4_KPARTS_LIBS} )<br />
</code><br />
<br />
Muuttujat, makrot ja muuta KDE:&auml; koskevaa hy&ouml;dyllist&auml; tietoa l&ouml;ytyy [[Development/KDE and CMake Together]] - sivulta.<br />
<br />
== CMaken Laajentaminen ==<br />
<br />
CMakea voi laajentaa k&auml;ytt&auml;m&auml;ll&auml; cmake komentojonoja. CMaken mukana tulee useita valmiita komentojonoja. UNIX pohjaisissa j&auml;rjestelmiss&auml; ne on asennettuna oletuksena /usr/local/share/CMake/Modules hakemistoon(riippuen CMaken asennushakemistosta). KDE kirjastot asentavat my&ouml;s joukon cmake laajennuksia share/apps/cmake/modules/ hakemistoon. KDE:n hakemistossa sijaitsevat laajennukset ohittavat j&auml;rjestelm&auml;nlaajuiset cmaken laajennukset. Ohjelmapakettien etsimist&auml; varten t&auml;&auml;ll&auml; on FindFOO.cmake tiedostot, katso lis&auml;tietoja [http://www.cmake.org/Wiki/CMake_HowToFindInstalledSoftware t&auml;&auml;lt&auml;]. CMaken kanssa on my&ouml;s mahdollista k&auml;ytt&auml;&auml; makroja, jotka ovat k&auml;ytt&ouml;kelpoisia useimpiin tilanteisiin joita ohjemien k&auml;&auml;nt&auml;misess&auml; tarvitaan.<br />
<br />
== autotools-pohjaisen KDE ohjelmiston k&auml;&auml;nt&auml;minen CMakelle ==<br />
<br />
Hakemistossa kdesdk/cmake/ on tiedosto nimelt&auml;&auml;n am2cmake. am2cmakea on ruby tiedosto, joten ruby tulee olla asennettu. Suorita am2cmake l&auml;hdekoodin p&auml;&auml;hakemistossa:<br />
<br />
<code><br />
$ cd src/mykooltool/<br />
$ am2cmake --kde4<br />
</code><br />
<br />
&Auml;l&auml; unohda "--kde4" - valitsinta, muuten am2cmake ei tuota KDE 4 ohjelmistoille sopivia tiedostoja. K&auml;&auml;nnetyt tiedostot 'voivat' toimia sellaisenaan k&auml;&auml;nt&auml;misen j&auml;lkeen, mutta monimutkaisemmat projektit yleens&auml; vaativat lis&auml;muokkauksia.<br />
<br />
Saatat joutua:<br />
<br />
* lis&auml;&auml;m&auml;&auml;n sis&auml;llytett&auml;via hakemistoja, k&auml;ytt&auml;en INCLUDE_DIRECTORIES()<br />
* lis&auml;&auml;m&auml;&auml;n linkkej&auml; kirjastoihin, k&auml;ytt&auml;en TARGET_LINK_LIBRARIES()<br />
* lis&auml;&auml;m&auml;&auml;n joitain m&auml;&auml;rittelyj&auml; k&auml;&auml;nt&auml;j&auml;lle, k&auml;ytt&auml;en ADD_DEFINITIONS()<br />
* lis&auml;&auml;m&auml;&auml;n tarkistuksia. Katso [[http://www.cmake.org/Wiki/CMake_HowToDoPlatformChecks Kuinka Tehd&auml; Ymp&auml;rist&ouml; Tarkistuksia] sek&auml; [http://www.cmake.org/Wiki/CMake_HowToFindInstalledSoftware Kuinka L&ouml;yt&auml;&auml; Asennettuja Ohjelmia]<br />
* huolehtimaan libtool-yhteensopivista kirjastoista. Ne eiv&auml;t ole tuettuina cmakessa, sen sijaan on ConvenienceLibs.cmake. T&auml;st&auml; tiedostosta l&ouml;yd&auml;t jokaiselle yhteensopivuus kirjastolle muuttujan, joka sis&auml;lt&auml;&auml; kaikki kyseisen yhteensopivuustiedoston l&auml;hteet.<br />
* am2cmake luo tiedoston nimelt&auml; AdditionalInfo.txt. T&auml;ss&auml; tiedostossa on lueteltu kaikki *.in ja *.in.in tiedostot kyseisest&auml; projektista. N&auml;iss&auml; tiedostoissa olevat asiat pit&auml;&auml; k&auml;&auml;nt&auml;&auml; k&auml;sin CMakelle.<br />
<br />
== Usein Kysyttyj&auml; Kysymyksi&auml; ==<br />
<br />
=== Kuinka voin opettaa k&auml;ytt&auml;m&auml;lleni tekstieditorille CMaken syntaksin ja sisennykset ? ===<br />
Katso CMake Winkin osiossa [http://www.cmake.org/Wiki/CMake_Editors_Support CMake Editors Support] on ohjeet Emacs (my&ouml;s XEmacs), VIM, Kate, KWrite, sek&auml; KDevelop editoreille.<br />
<br />
=== K&auml;&auml;nn&ouml;ksen aikana pit&auml;isi luoda er&auml;it&auml; tiedostoja. Kuinka ne tehd&auml;&auml;n ? ===<br />
K&auml;yt&auml;: ADD_CUSTOM_COMMAND(). Sen toiminta on selitetty CMake wikiss&auml;: [http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_generate_a_source_file_during_the_build.3F Kuinka luon l&auml;hdetiedoston k&auml;&auml;nn&ouml;n aikana]<br />
<br />
=== Minun pit&auml;isi k&auml;&auml;nt&auml;&auml; ohjelma jota k&auml;ytet&auml;&auml;n my&ouml;hemmin k&auml;&auml;nn&ouml;sty&ouml;ss&auml; luomaan tiedostoja. Kuinka t&auml;m&auml; tehd&auml;&auml;n ? ===<br />
Ajatellaan ett&auml; luotavan ohjelman nimi on genembed. K&auml;yt&auml; KDE4_ADD_EXECUTABLE(foo RUN_UNINSTALLED ${fooSources})luodaksesi k&auml;ynnistett&auml;v&auml; bin&auml;&auml;ri. RUN_UNINSTALLED on t&auml;rke&auml;, koska ohjelmaa ajetaan k&auml;&auml;nn&ouml;shakemistossa ja se pit&auml;&auml; linkitt&auml;&auml; k&auml;&auml;nn&ouml;shakemiston kirjastoihin. Suoritettava bin&auml;&auml;ri(ohjelma) on k&auml;&auml;nnetty RPATH asetusten mukaisesti ja on luotu suoritettava shellin komentojonotiedosto, samanniminen kuin ohjelma, mutta p&auml;&auml;tteell&auml; ".sh". Shellin komentojonotiedosto asettaa LD_LIBRARY_PATH muuttujan ja suorittaa varsinaisen ohjelman.<br />
K&auml;yt&auml; t&auml;t&auml; komentojonotiedostoa komennolla ADD_CUSTOM_COMMAND() kuten alla olevassa esimerkiss&auml;. Nimen ja tarkan sijainnin saat WRAPPER_SCRIPT muuttujasta.<br />
Esimerkki, kdelibs/kstyles/keramik/:a kopioitu esimerkki:<br />
<code><br />
# k&auml;&auml;nn&auml; ajettava bin&auml;&auml;ri<br />
KDE4_ADD_EXECUTABLE(genembed RUN_UNINSTALLED ${genembed_SRCS})<br />
<br />
# hae komentojonotiedoston nimi(joka asettaa LD_LIBRARY_PATH muuttujan)<br />
GET_TARGET_PROPERTY(GENEMBED_EXECUTABLE genembed WRAPPER_SCRIPT)<br />
<br />
# ja viimein oma komento<br />
ADD_CUSTOM_COMMAND(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/keramikrc.h<br />
COMMAND ${GENEMBED_EXECUTABLE} --file ${CMAKE_CURRENT_BINARY_DIR}/keramikPics.txt > \<br />
${CMAKE_CURRENT_BINARY_DIR}/pixmaps.keramik<br />
DEPENDS genembed ${keramikPics}<br />
)<br />
</code><br />
<br />
Kuten huomaat genembed on my&ouml;s listattu riippuvuudeksi, joka tarkoittaa ett&auml; cmake tiet&auml;&auml; ett&auml; sen on luotava bin&auml;&auml;ri nimelt&auml; genembed ennenkuin se voi suorittaa kyseisen oman komennon.<br />
<br />
=== En haluaisi k&auml;ytt&auml;&auml; -DCMAKE_INSTALL_PREFIX komentoriviparametri&auml;. Onko KDEDIR ymp&auml;rist&ouml;muuttuja tuettu CMakessa ? ===<br />
Ei. $KDEDIR on j&auml;&auml;m&auml;ss&auml; pois KDE 4:ss&auml;.<br />
<br />
=== Miksi saan k&auml;&auml;nt&auml;j&auml;virheit&auml; kuten /usr/lib/qt4/include/QtCore/qstring.h:536: undefined reference to `QString::fromLatin1_helper(char const*, int)'? ===<br />
Jos sinulla on vanha Qt4 versio qt/lib hakemistossa, sinun pit&auml;&auml; poistaa vanhat (4.0.1) tiedostot.<br />
<br />
=== Kuinka saan tehty&auml; &auml;&auml;nekk&auml;it&auml; Makefile tiedostoja? Haluan seurata tarkasti mik&auml; komento milloinkin on menossa. ===<br />
Anna VERBOSE muuttuja make:lle, esim:<br />
<code><br />
% make VERBOSE=1<br />
</code><br />
or<br />
<code><br />
% VERBOSE=1 make<br />
</code><br />
<br />
Lis&auml;tietoja, katso CMake wiki: [http://www.cmake.org/Wiki/CMake_FAQ#Is_there_an_option_to_produce_more_.27verbose.27_compiling.3F Is there an option to produce more 'verbose' compiling?]<br />
<br />
=== Makefiless&auml; ei ole 'make distclean' kohdetta. Kuinka siivoan pois kaikki, my&ouml;s v&auml;limuistissa olevat tiedostot ? ===<br />
Yksinkertaisesti, poista k&auml;&auml;nn&ouml;shakemisto, tai k&auml;&auml;nn&ouml;shakemiston sis&auml;lt&ouml;.<br />
<br />
[[Category:Programming]]<br />
[[Category:Tutorial]]<br />
[[Category:FAQs]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KXmlGuiWindow_(fi)&diff=19475Development/Tutorials/Using KXmlGuiWindow (fi)2008-01-10T19:42:22Z<p>Ozzi: Skandit kuntoon</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KXmlGuiWindow}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 2 - Main-ikkunan luonti|<br />
<br />
pre=[[Development/Tutorials/First_program (fi)|Perehdytys 1 - Hei maailma!]]|<br />
<br />
next=[[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]]| <br />
<br />
reading={{class|KXmlGuiWindow}}<br />
}}<br />
<br />
==Lyhyesti==<br />
T&auml;m&auml; perehdytys jatkaa [[Development/Tutorials/First_program (fi)|Hei Maailma]]-perehdytyksest&auml; perehdytt&auml;en {{class|KXmlGuiWindow}}-luokan k&auml;ytt&ouml;&ouml;n Main-ikkunan luomiseksi.<br />
<br />
Edellisess&auml; perehdytyksess&auml; k&auml;ytimme ikkunan luomiseksi pop-up-ikkuna tyylist&auml; valintaikkunaa mutta t&auml;ss&auml; on tarkoitus siirty&auml; askel l&auml;hemm&auml;ksi k&auml;ytt&ouml;kelpoista ohjelmaa.<br />
[[image:introtokdetutorial2.png|frame|center]]<br />
==Main-ikkuna==<br />
<br />
{{class|KXmlGuiWindow}}-luokka tuottaa oikean Main-ikkunan, valikko-, ty&ouml;kalu- ja tilariveineen sek&auml; tarjoaa keskelle tilan suurelle vimpaimelle(widget). Suurin osa KDE:n ohjelmista on sovellettu t&auml;st&auml; luokasta. {{class|KXmlGuiWindow}}-luokka tarjoaa yksinkertaisen tavan m&auml;&auml;ritell&auml; valikko- ja ty&ouml;kalurivit halutunlaisiksi XML-tiedostojen avulla (t&auml;m&auml; tekniikka on nimelt&auml;&auml;n XMLGUI). ''T&auml;ss&auml;'' perehdytyksess&auml; emme kumminkaan viel&auml; k&auml;yt&auml; XMLGUI:ta, vaan j&auml;t&auml;mme sen seuraavaan.<br />
<br />
Saadaksemme k&auml;ytt&ouml;kelpoisen Main-ikkunan, meid&auml;n tarvitsee alaluokittaa KXmlGuiWindow, joten luomme kaksi tiedostoa, <tt>mainwindow.cpp</tt> sek&auml; <tt>mainwindow.h</tt>, joihin sijoitamme alla olevat koodit.<br />
<br />
===mainwindow.h===<br />
<code cppqt n><br />
#ifndef MAINWINDOW_H<br />
#define MAINWINDOW_H<br />
<br />
#include <KXmlGuiWindow><br />
#include <KTextEdit><br />
<br />
class MainWindow : public KXmlGuiWindow<br />
{<br />
public:<br />
MainWindow(QWidget *parent=0);<br />
<br />
private:<br />
KTextEdit* textArea;<br />
};<br />
<br />
#endif<br />
</code><br />
Ensin teemme KXmlGuiWindow-luokasta aliluokan rivill&auml; 7: <tt>class MainWindow : public KXmlGuiWindow</tt>.<br />
<br />
Seuraavaksi luomme muodostajan: <tt>MainWindow(QWidget *parent=0);</tt>.<br />
<br />
Ja lopuksi luomme osoittimen joka osoittaa objektiin joka on p&auml;&auml;osassa ohjelmaamme. {{class|KTextEdit}} on yleinen richtext-editori muutamilla KDE:n hienouksilla, kuten automaattinen kursorin piilottaminen.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt n><br />
#include "mainwindow.h"<br />
<br />
MainWindow::MainWindow(QWidget *parent) : KXmlGuiWindow(parent)<br />
{<br />
textArea = new KTextEdit();<br />
setCentralWidget(textArea);<br />
setupGUI();<br />
}<br />
</code><br />
Ensimm&auml;isen&auml;, tietenkin, meid&auml;n tarvitsee sis&auml;llytt&auml;&auml; otsikkotiedosto jossa mainwindow-luokka on esitelty.<br />
<br />
Rivill&auml; 5 osoitetaan textArea uuteen richtext-editoriin. Seuraavaksi rivill&auml; 6 kutsutaan KXmlGuiWindow-objektin sis&auml;&auml;nrakennettua setCentralWidget()-funktiota joka kertoo KXmlGuiWindow-objektille ett&auml; ikkunan keskialueella n&auml;ytet&auml;&auml;n richtext-editori.<br />
<br />
Lopuksi kutsutaan KXmlGuiWindow::setupGUI()-funktiota joka huolehtii Main-ikkunan luomisessa tarvittavat asiat sek&auml; luo oletusvalikot(Asetukset, Ohje).<br />
<br />
==J&auml;lleen kerrran - main.cpp==<br />
Jotta saisimme otettua Main-ikkunan k&auml;ytt&ouml;&ouml;n, pit&auml;&auml; lis&auml;t&auml; muutama rivi edellisen perehdytyksen main.cpp-tiedostoon:<br />
<br />
===main.cpp===<br />
<code cppqt n><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
<br />
#include "mainwindow.h"<br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData( "tutorial2", 0,<br />
ki18n("Tutorial 2"), "1.0",<br />
ki18n("A simple text area"),<br />
KAboutData::License_GPL,<br />
ki18n("Copyright (c) 2007 Developer") );<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
<br />
KApplication app;<br />
<br />
MainWindow* window = new MainWindow();<br />
window->show();<br />
<br />
return app.exec();<br />
}<br />
</code><br />
Perehdytys 1 verrattuna uudet rivit ovat 5,18 ja 19. Rivill&auml; 18 luomme MainWindow-objektin ja rivill&auml; 19 se piirret&auml;&auml;n ruudulle.<br />
<br />
==CMake==<br />
Paras tapa k&auml;&auml;nt&auml;&auml; ohjelma on k&auml;ytt&auml;&auml; CMakea. Ainoat muutokset Perehdytys 1 n&auml;hdeon on ett&auml; <tt>mainwindow.cpp</tt> on lis&auml;tty l&auml;hdekoodilistaan ja <tt>tutorial1</tt> on muutettu <tt>tutorial2</tt>.<br />
<br />
===CMakeLists.txt===<br />
<code ini n><br />
project (tutorial2)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial2_SRCS <br />
main.cpp<br />
mainwindow.cpp<br />
)<br />
<br />
kde4_add_executable(tutorial2 ${tutorial2_SRCS})<br />
target_link_libraries(tutorial2 ${KDE4_KDEUI_LIBS})<br />
</code><br />
<br />
===K&auml;&auml;nt&auml;minen ja suoritus===<br />
K&auml;&auml;nn&auml;, linkit&auml; ja suorita seuraavasti:<br />
<code><br />
mkdir build && cd build<br />
cmake ..<br />
make<br />
./tutorial2<br />
</code><br />
<br />
==Seuraavaksi==<br />
Seuraavaksi voit siirty&auml; kohtaan [[Development/Tutorials/Using_KActions (fi)|Perehdytys 3 - KActions ja XMLGUI]].<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/First_program_(fi)&diff=19474Development/Tutorials/First program (fi)2008-01-10T19:41:18Z<p>Ozzi: /* Koodi */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/First_program}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 1 - Hei Maailma!|<br />
<br />
pre=[http://mindview.net/Books/TICPP/ThinkingInCPP2e.html C++], [http://www.trolltech.com/products/qt/ Qt], [[Getting_Started/Build/KDE4|KDE4 development environment]]|<br />
<br />
next=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]]| <br />
<br />
reading=[[Development/Tutorials/CMake (fi)|CMake]]<br />
}}<br />
<br />
==Lyhyesti==<br />
Ensimm&auml;isen ohjelmasi tulisi tervehti&auml; maailmaa "Hei Maailma!"-viestill&auml;, vai mit&auml;? T&auml;t&auml; tarkoitukseen k&auml;yt&auml;mme {{class|KMessageBox}}-luokkaa, ja muokkaamme yht&auml; painonappia.<br />
[[image:introtokdetutorial1.png|frame|center]]<br />
<br />
{{tip|Konqueror tarjoaa nopean tavan hankkia lis&auml;tietoja mist&auml; tahansa KDE:n luokasta. Esimerkiksi, jos haluat lis&auml;tietoja KMessageBox - luokasta, kirjoita Konquerorin osoitekentt&auml;&auml;n "kde:kmessagebox".}}<br />
<br />
{{tip|[http://www.kdevelop.org KDevelop] on erinomainen IDE kehitett&auml;ess&auml; KDE- ja Qt C++-sovelluksia. Se sis&auml;lt&auml;&auml; integroidun debuggerin, tehokkaan editorin syntaksikorostuksella, ''Projektivelho''n sovellusten luomiseksi mallinneista ja jopa luokkadokumentoinnit. Lis&auml;tietoja yksityiskohdista voi my&ouml;s l&ouml;yt&auml;&auml; [http://kdevelop.org/mediawiki/index.php/Main_Page KDevelop wiki] sivustossa.<br />
<br />
Ohjeita siit&auml; kuinka k&auml;ytt&auml;&auml; KDevelop-ohjelmaa KDE 4-sovellusten kanssa on saatavilla [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|t&auml;ll&auml; sivulla]]<br />
<br />
Silti sinun tarvitsee viel&auml; muokata [[Development/Tutorials/CMake_(fi)|CMake]] tiedostot k&auml;sin.<br />
}}<br />
<br />
==Koodi==<br />
Kaikki tarvittava koodi voidaan sijoittaa yhteen tiedostoon. Luo tiedosto <tt>main.cpp</tt> ja kopioi alla oleva koodi siihen:<br />
<code cppqt><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
#include <KMessageBox><br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData("tutorial1", // Ohjelman nimi järjestelmän käyttöön.<br />
0, // Nimi viestiluetteluun, käytä ohjelmannimeä jos nolla.<br />
ki18n("Tutorial 1"), // Näytettävä ohjelman nimi.<br />
"1.0", // Ohjelman versionumero. Merkkijono.<br />
ki18n("KMessageBox popup"), // Lyhyt kuvaus siitä mitä ohjelma tekee.<br />
KAboutData::License_GPL, // Lisenssin tunniste<br />
ki18n("(c) 2007"), // Tekijänoikeusmerkintä<br />
ki18n("Some text..."), // Vapaata teksti&auml;..<br />
"http://tutorial.com", // Ohjelman kotisivu.<br />
"submit@bugs.kde.org"); // Sähköpostiosoite bugien raportoimista varten.<br />
<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
KGuiItem guiItem( QString( "Hello" ), QString(),<br />
QString( "this is a tooltip" ),<br />
QString( "this is a whatsthis" ) );<br />
KMessageBox::questionYesNo( 0, "Hello World", "Hello", guiItem );<br />
}<br />
</code><br />
Ensimm&auml;inen KDE-luokka t&auml;ss&auml; ohjelmassa on {{class|KAboutData}}. T&auml;m&auml; luokka tallentaa ohjelman tiedot, kuten lyhyen kuvauksen, yll&auml;pit&auml;j&auml;tiedot, lisenssitiedot, jne. L&auml;hestulkoon kaikissa KDE ohjelmissa tulisi olla t&auml;m&auml; luokka.<br />
<br />
Seuraavana on {{class|KCmdLineArgs}}. T&auml;m&auml;n luokan tarkoituksena on m&auml;&auml;ritell&auml; komentorivin argumentit, esimerkiksi, avataksesi ohjelman tietyn tiedoston kanssa. Kuitenkin, t&auml;ss&auml; perehdytyksess&auml;, me yksinkertaisesti alustamme sen {{class|KAboutData}} objektilla, jonka ensimm&auml;isess&auml; kohdassa loimme, jotta voimme k&auml;ytt&auml;&auml; <tt>--version</tt> tai <tt>--author</tt> kytkimi&auml;.<br />
<br />
Kolmantena luomme {{class|KApplication}} objektin. T&auml;m&auml; on tarpeellinen jokaisessa ohjelmassa, koska esim. [[Development/Tutorials/Localization/i18n|i18n]] tarvitsee {{class|KApplication}}:n.<br />
<br />
Kaikki KDE:n vaatimat asettelut on nyt tehty ja voimme siirty&auml; tekem&auml;&auml;n mielenkiintoisempia asioita ohjelmallemme. Seuraavana on tarkoitus luoda pop-up-ikkuna sek&auml; muokata yht&auml; painonappia mieleiseksemme. Painonapin muokkauksessa k&auml;yt&auml;mme {{class|KGuiItem}}-objektia. {{class|KGuiItem}}:n ensimm&auml;inen parametri muodostajassa m&auml;&auml;rittelee painonapissa n&auml;ytett&auml;v&auml;n tekstin. Seuraava parametri m&auml;&auml;rittelisi {{class|KGuiItem}}:n ikonin, joka t&auml;ss&auml; tapauksessa on j&auml;tetty tyhj&auml;ksi antamalla argumentiksi <tt>QString()</tt>(tyhj&auml; QString). Viimeisen&auml; asetamme k&auml;yt&ouml;naikaisen vihjeen (joka n&auml;ytet&auml;&auml;n kun hiiren osoitin pys&auml;htyy hetkeksi objektin p&auml;&auml;lle) sek&auml; "Mik&auml; t&auml;m&auml; on?"-selvityksen(N&auml;ytet&auml;&auml;n hiiren oikean napin klikkauksen tai Shift-F1 kautta).<br />
<br />
Painonappi on nyt valmis ja voimme luoda pop-up-ikkunan. Me kutsumme <tt>{{class|KMessageBox}}::questionYesNo()</tt>-funktiota t&auml;h&auml;n tarkoitukseen, joka oletuksena luo viesti-ikkunan varustettuna "Kyll&auml;" ja "Ei" painonapeilla. Funktion toinen argumentti m&auml;&auml;rittelee tekstin j&auml;ka n&auml;ytet&auml;&auml;n keskell&auml; pop-up-laatikkoa. Kolmas argumentti kertoo funktiolle ikkunan nimen, ja viimeisen&auml; kerromme ett&auml; korvaamme "Yes"-painonapin luomallamme <tt>KGuiItem guiItem</tt> objektilla.<br />
<br />
Nyt olemme k&auml;yneet koodin l&auml;pi vaihe vaiheelta ja valmiit&auml; kokeilemaan k&auml;&auml;nt&auml;mist&auml; ja ohjelman suoritusta.<br />
<br />
==K&auml;&auml;nt&auml;minen==<br />
Jos olet asettanut ohjelmointiymp&auml;rist&ouml;si kuten [[Getting Started/Build/KDE4]]:ssa on neuvottu voit k&auml;&auml;nt&auml;&auml; koodin seuraavasti:<br />
<br />
<code><br />
g++ main.cpp -o tutorial1 \<br />
-I$QTDIR/include/Qt \<br />
-I$QTDIR/include/QtCore \<br />
-I$QTDIR/include \<br />
-I$KDEDIR/include/KDE \<br />
-I$KDEDIR/include \<br />
-L$KDEDIR/lib \<br />
-L$QTDIR/lib -lQtCore -lQtGui -lkdeui -lkdecore<br />
</code><br />
<br />
Ja ohjelman k&auml;ynnistys seuraavasti:<br />
<code><br />
dbus-launch ./tutorial1<br />
</code><br />
<br />
===CMaken k&auml;ytt&auml;minen===<br />
Jos edellinen k&auml;&auml;nn&ouml;s onnistui, voit kokeilla [[Development/Tutorials/CMake (fi)|CMaken]] k&auml;ytt&ouml;&auml;, kuten KDE 4 ymp&auml;rist&ouml;ss&auml; olisi tarkoitus. CMake automaattisesti etsii KDE:n, Qt:n, yms. kirjastot ja otsikkotiedostot sek&auml; tekee ohjelmistojesi k&auml;&auml;nt&auml;misen helpoksi muissakin j&auml;rjestelmiss&auml;.<br />
<br />
====CMakeLists.txt====<br />
Luo CMakeLists.txt-niminen tiedosto samaan hakemistoon jossa main.cpp sijaitsee ja kopioi alla oleva koodi siihen:<br />
<code ini n><br />
project (tutorial1)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial1_SRCS main.cpp)<br />
<br />
kde4_add_executable(tutorial1 ${tutorial1_SRCS})<br />
target_link_libraries(tutorial1 ${KDE4_KDEUI_LIBS})<br />
</code><br />
<tt>find_package()</tt>-funktio etsii haluamasi paketin, t&auml;ss&auml; tapauksessa KDE4 sek&auml; asettaa er&auml;it&auml; parametrej&auml; jotka selvitt&auml;v&auml;t paketin kirjastojen ja otsikkotiedostojen sijainnin. T&auml;ss&auml; tapauksessa k&auml;yt&auml;mme <tt>KDE4_INCLUDES</tt>-muuttujaa jossa on tieto KDE4:n otsikkotiedostojen sijainnista.<br />
<br />
Jotta k&auml;&auml;nt&auml;j&auml; l&ouml;yt&auml;isi n&auml;m&auml; otsikkotiedostot, annamme t&auml;m&auml;n muuttujan <tt>include_directories()</tt>-funktiolle, joka lis&auml;&auml; KDE4 otsikkotiedostot otsikkotiedostojen etsint&auml;polkuun.<br />
<br />
Seuraavana luomme <tt>tutorial1_SRCS</tt>-nimisen muuttujan <tt>set()</tt>-funktiota apuna k&auml;ytt&auml;en. Muuttujan arvoksi tulee l&auml;hdekooditiedostomme nimi.<br />
<br />
<tt>kde4_add_executable()</tt>-funktiokutsun avulla luomme <tt>tutorial1</tt>-nimisen suoritettavan bin&auml;&auml;rin l&auml;hdekooditiedostoista jotka on m&auml;&auml;ritelty <tt>tutorial1_SRCS</tt>-muuttujassa. Viimeisen&auml; linkit&auml;mme suoritettavan bin&auml;&auml;ritiedoston <tt>target_link_libraries()</tt>-funktiota sek&auml; <tt>KDE4_KDEUI_LIBS</tt> muuttujia apuna k&auml;ytt&auml;en KDE4 kdeui-kirjastoon. <tt>KDE4_KDEUI_LIBS</tt> muuttuja luotiin my&ouml;s <tt>find_package()</tt>-funktiossa.<br />
<br />
====K&auml;&auml;nn&ouml;s ja suoritus====<br />
Edelleen, jos olet asettanut ohjelmointiymp&auml;rist&ouml;si kuten [[Getting Started/Build/KDE4]]:ssa on neuvottu voit k&auml;&auml;nt&auml;&auml; koodin seuraavasti:<br />
<code><br />
cmakekde<br />
</code><br />
<br />
tai ellet, niin:<br />
<code><br />
mkdir build && cd build<br />
cmake ..<br />
make<br />
</code><br />
<br />
Ja suoritus:<br />
<code><br />
./tutorial1<br />
</code><br />
<br />
==Seuraavaksi==<br />
Seuraavaksi voit jatkaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|Main-ikkunan luonti]] - perehdytykseen.<br />
<br />
[[Category:C++]]</div>Ozzihttps://techbase.kde.org/index.php?title=Development/Tutorials/First_program_(fi)&diff=19473Development/Tutorials/First program (fi)2008-01-10T19:39:40Z<p>Ozzi: Skandit kuntoon</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/First_program}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Perehdytys 1 - Hei Maailma!|<br />
<br />
pre=[http://mindview.net/Books/TICPP/ThinkingInCPP2e.html C++], [http://www.trolltech.com/products/qt/ Qt], [[Getting_Started/Build/KDE4|KDE4 development environment]]|<br />
<br />
next=[[Development/Tutorials/Using_KXmlGuiWindow (fi)|Perehdytys 2 - Main-ikkunan luonti]]| <br />
<br />
reading=[[Development/Tutorials/CMake (fi)|CMake]]<br />
}}<br />
<br />
==Lyhyesti==<br />
Ensimm&auml;isen ohjelmasi tulisi tervehti&auml; maailmaa "Hei Maailma!"-viestill&auml;, vai mit&auml;? T&auml;t&auml; tarkoitukseen k&auml;yt&auml;mme {{class|KMessageBox}}-luokkaa, ja muokkaamme yht&auml; painonappia.<br />
[[image:introtokdetutorial1.png|frame|center]]<br />
<br />
{{tip|Konqueror tarjoaa nopean tavan hankkia lis&auml;tietoja mist&auml; tahansa KDE:n luokasta. Esimerkiksi, jos haluat lis&auml;tietoja KMessageBox - luokasta, kirjoita Konquerorin osoitekentt&auml;&auml;n "kde:kmessagebox".}}<br />
<br />
{{tip|[http://www.kdevelop.org KDevelop] on erinomainen IDE kehitett&auml;ess&auml; KDE- ja Qt C++-sovelluksia. Se sis&auml;lt&auml;&auml; integroidun debuggerin, tehokkaan editorin syntaksikorostuksella, ''Projektivelho''n sovellusten luomiseksi mallinneista ja jopa luokkadokumentoinnit. Lis&auml;tietoja yksityiskohdista voi my&ouml;s l&ouml;yt&auml;&auml; [http://kdevelop.org/mediawiki/index.php/Main_Page KDevelop wiki] sivustossa.<br />
<br />
Ohjeita siit&auml; kuinka k&auml;ytt&auml;&auml; KDevelop-ohjelmaa KDE 4-sovellusten kanssa on saatavilla [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|t&auml;ll&auml; sivulla]]<br />
<br />
Silti sinun tarvitsee viel&auml; muokata [[Development/Tutorials/CMake_(fi)|CMake]] tiedostot k&auml;sin.<br />
}}<br />
<br />
==Koodi==<br />
Kaikki tarvittava koodi voidaan sijoittaa yhteen tiedostoon. Luo tiedosto <tt>main.cpp</tt> ja kopioi alla oleva koodi siihen:<br />
<code cppqt><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KCmdLineArgs><br />
#include <KMessageBox><br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData("tutorial1", // Ohjelman nimi j&auml;rjestelm&auml;n k&auml;ytt&ouml;&ouml;n.<br />
0, // Nimi viestiluetteluun, k&auml;yt&auml; ohjelmannime&auml; jos nolla.<br />
ki18n("Tutorial 1"), // N&auml;ytett&auml;v&auml; ohjelman nimi.<br />
"1.0", // Ohjelman versionumero. Merkkijono.<br />
ki18n("KMessageBox popup"), // Lyhyt kuvaus siit&auml; mit&auml; ohjelma tekee.<br />
KAboutData::License_GPL, // Lisenssin tunniste<br />
ki18n("(c) 2007"), // Tekij&auml;noikeusmerkint&auml;<br />
ki18n("Some text..."), // Vapaata teksti&auml;..<br />
"http://tutorial.com", // Ohjelman kotisivu.<br />
"submit@bugs.kde.org"); // S&auml;hk&ouml;postiosoite bugien raportoimista varten.<br />
<br />
KCmdLineArgs::init( argc, argv, &aboutData );<br />
KApplication app;<br />
KGuiItem guiItem( QString( "Hello" ), QString(),<br />
QString( "this is a tooltip" ),<br />
QString( "this is a whatsthis" ) );<br />
KMessageBox::questionYesNo( 0, "Hello World", "Hello", guiItem );<br />
}<br />
</code><br />
Ensimm&auml;inen KDE-luokka t&auml;ss&auml; ohjelmassa on {{class|KAboutData}}. T&auml;m&auml; luokka tallentaa ohjelman tiedot, kuten lyhyen kuvauksen, yll&auml;pit&auml;j&auml;tiedot, lisenssitiedot, jne. L&auml;hestulkoon kaikissa KDE ohjelmissa tulisi olla t&auml;m&auml; luokka.<br />
<br />
Seuraavana on {{class|KCmdLineArgs}}. T&auml;m&auml;n luokan tarkoituksena on m&auml;&auml;ritell&auml; komentorivin argumentit, esimerkiksi, avataksesi ohjelman tietyn tiedoston kanssa. Kuitenkin, t&auml;ss&auml; perehdytyksess&auml;, me yksinkertaisesti alustamme sen {{class|KAboutData}} objektilla, jonka ensimm&auml;isess&auml; kohdassa loimme, jotta voimme k&auml;ytt&auml;&auml; <tt>--version</tt> tai <tt>--author</tt> kytkimi&auml;.<br />
<br />
Kolmantena luomme {{class|KApplication}} objektin. T&auml;m&auml; on tarpeellinen jokaisessa ohjelmassa, koska esim. [[Development/Tutorials/Localization/i18n|i18n]] tarvitsee {{class|KApplication}}:n.<br />
<br />
Kaikki KDE:n vaatimat asettelut on nyt tehty ja voimme siirty&auml; tekem&auml;&auml;n mielenkiintoisempia asioita ohjelmallemme. Seuraavana on tarkoitus luoda pop-up-ikkuna sek&auml; muokata yht&auml; painonappia mieleiseksemme. Painonapin muokkauksessa k&auml;yt&auml;mme {{class|KGuiItem}}-objektia. {{class|KGuiItem}}:n ensimm&auml;inen parametri muodostajassa m&auml;&auml;rittelee painonapissa n&auml;ytett&auml;v&auml;n tekstin. Seuraava parametri m&auml;&auml;rittelisi {{class|KGuiItem}}:n ikonin, joka t&auml;ss&auml; tapauksessa on j&auml;tetty tyhj&auml;ksi antamalla argumentiksi <tt>QString()</tt>(tyhj&auml; QString). Viimeisen&auml; asetamme k&auml;yt&ouml;naikaisen vihjeen (joka n&auml;ytet&auml;&auml;n kun hiiren osoitin pys&auml;htyy hetkeksi objektin p&auml;&auml;lle) sek&auml; "Mik&auml; t&auml;m&auml; on?"-selvityksen(N&auml;ytet&auml;&auml;n hiiren oikean napin klikkauksen tai Shift-F1 kautta).<br />
<br />
Painonappi on nyt valmis ja voimme luoda pop-up-ikkunan. Me kutsumme <tt>{{class|KMessageBox}}::questionYesNo()</tt>-funktiota t&auml;h&auml;n tarkoitukseen, joka oletuksena luo viesti-ikkunan varustettuna "Kyll&auml;" ja "Ei" painonapeilla. Funktion toinen argumentti m&auml;&auml;rittelee tekstin j&auml;ka n&auml;ytet&auml;&auml;n keskell&auml; pop-up-laatikkoa. Kolmas argumentti kertoo funktiolle ikkunan nimen, ja viimeisen&auml; kerromme ett&auml; korvaamme "Yes"-painonapin luomallamme <tt>KGuiItem guiItem</tt> objektilla.<br />
<br />
Nyt olemme k&auml;yneet koodin l&auml;pi vaihe vaiheelta ja valmiit&auml; kokeilemaan k&auml;&auml;nt&auml;mist&auml; ja ohjelman suoritusta.<br />
<br />
==K&auml;&auml;nt&auml;minen==<br />
Jos olet asettanut ohjelmointiymp&auml;rist&ouml;si kuten [[Getting Started/Build/KDE4]]:ssa on neuvottu voit k&auml;&auml;nt&auml;&auml; koodin seuraavasti:<br />
<br />
<code><br />
g++ main.cpp -o tutorial1 \<br />
-I$QTDIR/include/Qt \<br />
-I$QTDIR/include/QtCore \<br />
-I$QTDIR/include \<br />
-I$KDEDIR/include/KDE \<br />
-I$KDEDIR/include \<br />
-L$KDEDIR/lib \<br />
-L$QTDIR/lib -lQtCore -lQtGui -lkdeui -lkdecore<br />
</code><br />
<br />
Ja ohjelman k&auml;ynnistys seuraavasti:<br />
<code><br />
dbus-launch ./tutorial1<br />
</code><br />
<br />
===CMaken k&auml;ytt&auml;minen===<br />
Jos edellinen k&auml;&auml;nn&ouml;s onnistui, voit kokeilla [[Development/Tutorials/CMake (fi)|CMaken]] k&auml;ytt&ouml;&auml;, kuten KDE 4 ymp&auml;rist&ouml;ss&auml; olisi tarkoitus. CMake automaattisesti etsii KDE:n, Qt:n, yms. kirjastot ja otsikkotiedostot sek&auml; tekee ohjelmistojesi k&auml;&auml;nt&auml;misen helpoksi muissakin j&auml;rjestelmiss&auml;.<br />
<br />
====CMakeLists.txt====<br />
Luo CMakeLists.txt-niminen tiedosto samaan hakemistoon jossa main.cpp sijaitsee ja kopioi alla oleva koodi siihen:<br />
<code ini n><br />
project (tutorial1)<br />
<br />
find_package(KDE4 REQUIRED)<br />
include_directories(${KDE4_INCLUDES})<br />
<br />
set(tutorial1_SRCS main.cpp)<br />
<br />
kde4_add_executable(tutorial1 ${tutorial1_SRCS})<br />
target_link_libraries(tutorial1 ${KDE4_KDEUI_LIBS})<br />
</code><br />
<tt>find_package()</tt>-funktio etsii haluamasi paketin, t&auml;ss&auml; tapauksessa KDE4 sek&auml; asettaa er&auml;it&auml; parametrej&auml; jotka selvitt&auml;v&auml;t paketin kirjastojen ja otsikkotiedostojen sijainnin. T&auml;ss&auml; tapauksessa k&auml;yt&auml;mme <tt>KDE4_INCLUDES</tt>-muuttujaa jossa on tieto KDE4:n otsikkotiedostojen sijainnista.<br />
<br />
Jotta k&auml;&auml;nt&auml;j&auml; l&ouml;yt&auml;isi n&auml;m&auml; otsikkotiedostot, annamme t&auml;m&auml;n muuttujan <tt>include_directories()</tt>-funktiolle, joka lis&auml;&auml; KDE4 otsikkotiedostot otsikkotiedostojen etsint&auml;polkuun.<br />
<br />
Seuraavana luomme <tt>tutorial1_SRCS</tt>-nimisen muuttujan <tt>set()</tt>-funktiota apuna k&auml;ytt&auml;en. Muuttujan arvoksi tulee l&auml;hdekooditiedostomme nimi.<br />
<br />
<tt>kde4_add_executable()</tt>-funktiokutsun avulla luomme <tt>tutorial1</tt>-nimisen suoritettavan bin&auml;&auml;rin l&auml;hdekooditiedostoista jotka on m&auml;&auml;ritelty <tt>tutorial1_SRCS</tt>-muuttujassa. Viimeisen&auml; linkit&auml;mme suoritettavan bin&auml;&auml;ritiedoston <tt>target_link_libraries()</tt>-funktiota sek&auml; <tt>KDE4_KDEUI_LIBS</tt> muuttujia apuna k&auml;ytt&auml;en KDE4 kdeui-kirjastoon. <tt>KDE4_KDEUI_LIBS</tt> muuttuja luotiin my&ouml;s <tt>find_package()</tt>-funktiossa.<br />
<br />
====K&auml;&auml;nn&ouml;s ja suoritus====<br />
Edelleen, jos olet asettanut ohjelmointiymp&auml;rist&ouml;si kuten [[Getting Started/Build/KDE4]]:ssa on neuvottu voit k&auml;&auml;nt&auml;&auml; koodin seuraavasti:<br />
<code><br />
cmakekde<br />
</code><br />
<br />
tai ellet, niin:<br />
<code><br />
mkdir build && cd build<br />
cmake ..<br />
make<br />
</code><br />
<br />
Ja suoritus:<br />
<code><br />
./tutorial1<br />
</code><br />
<br />
==Seuraavaksi==<br />
Seuraavaksi voit jatkaa [[Development/Tutorials/Using_KXmlGuiWindow (fi)|Main-ikkunan luonti]] - perehdytykseen.<br />
<br />
[[Category:C++]]</div>Ozzi