https://techbase.kde.org/api.php?action=feedcontributions&user=Powerfox&feedformat=atomKDE TechBase - User contributions [en]2024-03-19T02:52:55ZUser contributionsMediaWiki 1.40.2https://techbase.kde.org/index.php?title=Contribute/Get_a_Contributor_Account&diff=39296Contribute/Get a Contributor Account2009-03-08T20:29:04Z<p>Powerfox: /* Getting the SSH keys */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Contribute/Get a SVN Account}}<br />
This tutorial is about how to apply for a SVN account for KDE.<br />
<br />
== Notations ==<br />
<br />
* The word ''SVN'' applies to all SVN servers.<br />
* The phrase ''KDE SVN'' refers only to KDE's SVN server.<br />
* The phrase ''anonymous SVN'' means KDE's anonymous SVN mirrors.<br />
<br />
== What is KDE SVN? ==<br />
<br />
To have write access to KDE SVN, you have to use the main SVN server of KDE. (Anonymous SVN uses mirrors of this server. SVN does not allow you to read from one server and write to another.)<br />
<br />
To be able to use the main KDE SVN server, you need an account there. An account is made up of a ''username'' (normally your family name), a password and an email address. The username is for getting in, the password for authenticating and the email address for knowing who to contact if another developer wants to contact the account holder. (The username is sometimes known also as the ''login''.)<br />
<br />
'''Note''': you can see the accounts in [http://websvn.kde.org/trunk/kde-common/accounts kde-common/accounts]. That is the list of all accounts. Yes, '''the account list is public''', for example on [http://websvn.kde.org WebSVN].<br />
<br />
To access the main KDE SVN, you have two possibilities, with different ways to encrypt transmitted data:<br />
* using HTTPS<br />
* using SSH<br />
<br />
If you have never used ssh before, you might prefer ''HTTPS'', it's a bit simpler to set up. <br />
<br />
However it seems that currently svn-over-ssh is really much faster than svn-over-https, so that is a good reason for using ssh.<br />
<br />
The password you will need to create depends on the above:<br />
* a normal password for accessing by HTTPS, or<br />
* a SSH public key for accessing by SSH<br />
<br />
A KDE SVN account allows you to write to nearly anywhere in the KDE SVN. However, there are exceptions:<br />
* the KDE SVN internals<br />
* the admin directory<br />
* the www module (exceptions can be made for this.)<br />
<br />
== Who Can Apply For a KDE SVN Account? ==<br />
<br />
Normally, any developer who has done some work on KDE can apply for a KDE SVN account.<br />
<br />
Translators should get approval from their team leader so that they can organize how the work is being done in his/her team. Please mention the approval from the team leader when requesting the account.<br />
<br />
Please also [[Policies/SVN Commit Policy|read the KDE SVN commit policy]]. You must accept these rules when using your future KDE SVN account.<br />
<br />
Also please apply for an account only if you think that you will work on KDE for a somewhat longer time. If you know that you will only work for a couple of weeks and then never again, please consider not applying for a KDE SVN account but still, do continue to send patches.<br />
<br />
The limitations are not there to exclude anyone - they are there to ensure that the maintenance of accounts remains reasonable.<br />
<br />
Of course, to be clear: ''the [mailto:sysadmin@kde.org KDE's sysadmins] have the last word about whether or not to create a KDE SVN account for somebody''.<br />
<br />
== Choosing a Password ==<br />
<br />
This section assumes that you want access via HTTPS (without SSH). Otherwise skip this section.<br />
<br />
First you have to choose a password. If possible, one that you do not use for anything else on your computer (as the SVN account has nothing to do with any other account on your computer.)<br />
<br />
In any case, please use ''common precautions'' about passwords.<br />
<br />
Strong passwords:<br />
* have both upper and lower case letters.<br />
* have digits and/or punctuation characters as well as letters.<br />
* are easy to remember, so they do not have to be written down.<br />
* are at least eight characters long.<br />
<br />
A strong password is '''not''':<br />
<br />
* Personal information such as your name, phone number, social security number, birth date or address. Even names of acquaintances and the like should not be used.<br />
* Any word in the dictionary, or based closely on such a word (such as a word spelled backwards).<br />
* A word with letters simply replaced by digits. For example, bl0wf1sh is not a strong password.<br />
* Easy to spot while you're typing them in. Passwords like 12345, qwerty (i.e., all keys right next to each other), or nnnnnn should be avoided.<br />
<br />
All the rules are not here to annoy you but to guarantee a certain level of security for the KDE SVN server.<br />
<br />
== Getting the Encoded Password ==<br />
<br />
This section assumes that you want access via HTTPS (without SSH). Otherwise skip this section.<br />
<br />
Now that you have your password, you need to encode it, not to have to send it in clear. (Note: this encryption is the same type of encryption used by many Linux distributions for their {{path|/etc/shadow}} file.)<br />
<br />
If your password is 8 characters long, one way to do this would be using Perl: <!-- <code>perl -e "print crypt('&lt;your password&gt;','xy'),\"\n\";"</code> --><br />
<nowiki>perl -e 'print crypt("<your password>","\$1\$xyz\$")."\n";'</nowiki><br />
where &lt;your password&gt; has to be replaced with your password and ''xyz'' with 3 to 8 random characters of your choice. Leave the \$1\$ before it and the \$ after it.<br />
<br />
(Hint: $ must be "escaped" with a backslash. For instance: If your password is "abc$123" you have to replace &lt;your password&gt; with "abc\$123". )<br />
<br />
'''Note''': do not worry to find your choice of &lt;xyz&gt; at the start of the encoded password, it is meant to be so.<br />
<br />
Another solution is to create a dummy account on a Unix system where you have administrator access. You can use the built-in user management programs of your distribution and search for the account in your file {{path|/etc/shadow}} or you can use the following code:<br />
useradd dummy; passwd dummy; grep dummy /etc/passwd /etc/shadow; userdel dummy<br />
<br />
In any case, the password is then the part between the first ':' and the second ':'. (Note: not a star! (*) That means that it is not the password!)<br />
<br />
Save the encoded password so that you can use it later in the application.<br />
<br />
== Getting the SSH keys ==<br />
<br />
This section assumes that you want access via SSH (not with HTTPS). Otherwise skip this section.<br />
<br />
Please refer to a SSH documentation or book to see how to create a pair of SSH keys, the short version is <code bash>ssh-keygen -t dsa</code><br />
The '-t dsa' indicates that 'dsa' type keys should be created. Dsa and rsa keys are used in the version 2 of the SSH protocol, whereas rsa keys are used in version 1. See the [http://www.openbsd.org/cgi-bin/man.cgi?query=ssh-keygen ssh documentation] for more. Accept the default filename and the default of no passphrase.<br />
<br />
You '''need''' a SSH public key. Don't send us a GPG (OpenPGP) key, that is completely unrelated!<br />
<br />
The password in the sense of this documentation is the '''public key''' that you are creating. The public key can usually be found at {{path|$HOME/.ssh/id_dsa.pub}}. <br />
<br />
Do '''not''' send the private key at {{path|$HOME/.ssh/id_dsa}}, it has to remain a secret.<br />
<br />
You should also set up <tt>ssh-agent</tt> so you do not have to type the password every time. There are several tutorials available explaining how to do this, for example [http://mah.everybody.org/docs/ssh this one].<br />
<br />
'''Note''': if you already have an ssh key, you can just use the extisting key instead of creating a new one. <br />
<br />
{{tip|<br />
If you want to use SVN with SSH with another user than the one who created the keys, you need to copy <tt>$HOME/.ssh/id_dsa.pub</tt> and <tt>$HOME/.ssh/id_dsa</tt> to the other user's <tt>$HOME/.ssh</tt> directory.<br />
<br />
You should probably also backup those files.<br />
}}<br />
<br />
=== Setting up SVN+SSH protocol ===<br />
<br />
Once you created your key, you'll have to tell SSH that this one should be used for all connections to KDE sites. Add the following lines to the <tt>~/.ssh/config</tt> file. Replace USERNAME with yours.<br />
<br />
<pre><br />
Host *.kde.org<br />
User USERNAME<br />
IdentityFile ~/.ssh/id_dsa<br />
</pre><br />
<br />
The linked IdentityFile must belong to the public key you send in when applying for the SVN account. But it is ''not'' the public key (<tt>*.pub</tt>).<br />
<br />
== Apply for an account ==<br />
<br />
Now that you have a password, you need a username for your KDE SVN account. Normally your family name is used. Let us call it ''username'' for this example.<br />
<br />
You can propose something else if you want. But be careful that one day, you could ask for a KDE email address and this would be the base for your address. For example: <tt>username@kde.org</tt>. (Note, however, that KDE email addresses are not granted so easily anymore, as too many people have ranted with a KDE address and other people thought that it was the official position of the KDE Team. In the meantime, [http://www.kdemail.net KDE Mail] was created for if you need a permanent address.)<br />
<br />
So now you have a username and a password. Now the email address: you have to use your own (be it a normal address or a KDE Mail address). Of course, do not forget that this '''email address becomes public''' (at least by [http://websvn.kde.org WebSVN]) so you will unfortunately get spam.<br />
<br />
Also note that this email address should be the same one that you use on [http://bugs.kde.org bugs.kde.org]. If you don't have one, please create it so that it can be given usual developer rights. Closing bug reports with keywords in commit comments only works if the email address of your Subversion and [http://bugs.kde.org bugs.kde.org] accounts match.<br />
<br />
Now you are ready to apply for for a KDE SVN account.<br />
Go to [https://sysadmin.kde.org/svnaccount/ https://sysadmin.kde.org/svnaccount/] and fill out the form. It should be easy to do now.<br />
<br />
After filling out the form, you will receive an email with a link to click on. This is done to verify your email address. The application is not complete before you click on it. <br />
<br />
Also note that the form will ask you who has encouraged you to apply. He or she will also get an email to verify your request.<br />
<br />
The form also holds a field ''justification'', here you can explain what you want to do with your future KDE SVN account, like for examples developing a certain application, making documentations, being team leader of a translation...<br />
<br />
== And Now? ==<br />
<br />
After having sent the form and clicking the link in the email, you have to wait for the answer (typically within two or three days).<br />
<br />
Once you have confirmation that your account has been created, you need to adapt your local copy to the new server. See the [[Contribute/First Steps with your KDE SVN Account|next tutorial]] for your first steps with your new account.<br />
<br />
Please add your geographical location (what country are you in?) and other details at the [http://commit-digest.org/data/ Commit Digest data page] so that the Commit Digest can accurately reflect who is working where.</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Debugging/Using_Error_Messages&diff=32427Development/Tutorials/Debugging/Using Error Messages2008-08-28T13:08:51Z<p>Powerfox: /* Links */</p>
<hr />
<div>{{Template:I18n/Language_Navigation_Bar|Development/Tutorials/Debugging/Using Error Messages}}<br />
<br />
When you start a konsole and type the commands to start an application you<br />
will see all sorts of statements are printed in the konsole while the <br />
application is running. All applications print these messages, to look<br />
at them you have to know where to look. The application will have to be<br />
compiled with the debugging enabled. So using a precompiled package from a distribution<br />
probably will not give you this information. If you compiled the application <br />
yourself, make sure the configure option "<tt>--disable-debug</tt>" was not used.<br />
<br />
In KDE all debugging text-output can be switched on or off based on so<br />
called '''areas'''. One application can be one or more area. One part of the kde base libraries can be another area. Enabling/disabling these areas from being printed can be done using the '''kdebugdialog''' application. For simple debugging selecting all<br />
sections is probably wise.<br />
<br />
When you are debugging it is best to simply start a konsole and start the<br />
application from there. In a konsole you could simply type:<br />
<br />
kicker<br />
<br />
and in the konsole kicker could return a message like:<br />
<br />
ERROR: kicker is already running!<br />
<br />
When a lot of output is written to the konsole it might go out of view before<br />
you could read it, therefor it is easy to create a text file which contains<br />
all this information, to do so type the following:<br />
<br />
application 2&gt;&amp;1 | tee debug.log<br />
<br />
where 'application' can be replaced with the application you are debugging.<br />
Afterwards you could open the file 'debug.log' to look at the messages again.<br />
<br />
If you are NOT starting the application from a konsole the messages will be<br />
logged somewhere else, or they could have been discarded by the program that<br />
started your application. <br />
<br />
If your application is started by clicking on an icon your best bet is to check<br />
the following log files. Beware; they contain logs for a lot of applications, <br />
not just the application you are debugging!<br />
<br />
'''Case 1: Graphical login (i.e. kdm, gdm, xdm, etc.'''<br />
<br />
The debug messages get redirected into the file {{path|~/.xsession-errors}} or<br />
{{path|~/.X.err}} in your home directory (that is with a leading dot '.' also<br />
watch the Capital).<br />
<br />
'''Case 2: You are using startx:'''<br />
<br />
Use the following command to restart your session:<br />
startx 2&gt;&amp;1 | tee startx.log<br />
<br />
so that all the debug messages of applications started at KDE's startup (and<br />
any application launched from the panel etc.) go to the file "startx.log"<br />
<br />
== Links ==<br />
<br />
The debug messages are usually printed in C++ with the kDebug or kWarning statement. Example:<br />
<br />
kDebug(1210) << "arbitrary message";<br />
kWarning(1210) << "this rather should not happen";<br />
<br />
The number 1210 (so called ''debug area'') in this case represents kicker. You can omit the number.<br />
<br />
See also: [http://api.kde.org/4.0-api/kdelibs-apidocs/kdecore/html/group__kdebug.html kDebug/kWarning API documentation] and [http://websvn.kde.org/trunk/KDE/kdelibs/kdecore/kdebug.areas?view=markup kdebug.areas] for list of debug areas numbers.<br />
Note that you can use add_definition(-DKDE_DEFAULT_DEBUG_AREA=<number> ) in CmakeLists.txt to specify default debug area.<br />
<br />
''Initial Author:'' [mailto:zander@kde.org Thomas Zander]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Debugging/Using_Error_Messages&diff=32426Development/Tutorials/Debugging/Using Error Messages2008-08-28T13:08:11Z<p>Powerfox: /* Links */ Note about kdebug.areas</p>
<hr />
<div>{{Template:I18n/Language_Navigation_Bar|Development/Tutorials/Debugging/Using Error Messages}}<br />
<br />
When you start a konsole and type the commands to start an application you<br />
will see all sorts of statements are printed in the konsole while the <br />
application is running. All applications print these messages, to look<br />
at them you have to know where to look. The application will have to be<br />
compiled with the debugging enabled. So using a precompiled package from a distribution<br />
probably will not give you this information. If you compiled the application <br />
yourself, make sure the configure option "<tt>--disable-debug</tt>" was not used.<br />
<br />
In KDE all debugging text-output can be switched on or off based on so<br />
called '''areas'''. One application can be one or more area. One part of the kde base libraries can be another area. Enabling/disabling these areas from being printed can be done using the '''kdebugdialog''' application. For simple debugging selecting all<br />
sections is probably wise.<br />
<br />
When you are debugging it is best to simply start a konsole and start the<br />
application from there. In a konsole you could simply type:<br />
<br />
kicker<br />
<br />
and in the konsole kicker could return a message like:<br />
<br />
ERROR: kicker is already running!<br />
<br />
When a lot of output is written to the konsole it might go out of view before<br />
you could read it, therefor it is easy to create a text file which contains<br />
all this information, to do so type the following:<br />
<br />
application 2&gt;&amp;1 | tee debug.log<br />
<br />
where 'application' can be replaced with the application you are debugging.<br />
Afterwards you could open the file 'debug.log' to look at the messages again.<br />
<br />
If you are NOT starting the application from a konsole the messages will be<br />
logged somewhere else, or they could have been discarded by the program that<br />
started your application. <br />
<br />
If your application is started by clicking on an icon your best bet is to check<br />
the following log files. Beware; they contain logs for a lot of applications, <br />
not just the application you are debugging!<br />
<br />
'''Case 1: Graphical login (i.e. kdm, gdm, xdm, etc.'''<br />
<br />
The debug messages get redirected into the file {{path|~/.xsession-errors}} or<br />
{{path|~/.X.err}} in your home directory (that is with a leading dot '.' also<br />
watch the Capital).<br />
<br />
'''Case 2: You are using startx:'''<br />
<br />
Use the following command to restart your session:<br />
startx 2&gt;&amp;1 | tee startx.log<br />
<br />
so that all the debug messages of applications started at KDE's startup (and<br />
any application launched from the panel etc.) go to the file "startx.log"<br />
<br />
== Links ==<br />
<br />
The debug messages are usually printed in C++ with the kDebug or kWarning statement. Example:<br />
<br />
kDebug(1210) << "arbitrary message";<br />
kWarning(1210) << "this rather should not happen";<br />
<br />
The number 1210 (so called ''debug area'') in this case represents kicker. You can omit the number.<br />
<br />
See also: [http://api.kde.org/4.0-api/kdelibs-apidocs/kdecore/html/group__kdebug.html kDebug/kWarning API documentation] and [http://websvn.kde.org/trunk/KDE/kdelibs/kdecore/kdebug.areas?view=markup] for list of debug areas numbers.<br />
Note that you can use add_definition(-DKDE_DEFAULT_DEBUG_AREA=<number> ) in CmakeLists.txt to specify default debug area.<br />
<br />
''Initial Author:'' [mailto:zander@kde.org Thomas Zander]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Debugging/Debugging_with_GDB&diff=28597Development/Tutorials/Debugging/Debugging with GDB2008-06-20T15:31:24Z<p>Powerfox: /* Debugging core files with GDB */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Debugging/Debugging with GDB}}<br />
This is a short tutorial on debugging KDE applications. Throughout this<br />
tutorial I will use "kedit" as an example application.<br />
<br />
==Debugging with GDB==<br />
<br />
The recommended version of gdb to use is version 4.95 or higher; older<br />
versions have problems generating proper backtraces.<br />
<br />
There are three ways to debug an application with gdb:<br />
<br />
# You can start the application from within gdb.<br />
# You can attach gdb to an already running application.<br />
# You can run gdb after an application has crashed using a core file.<br />
<br />
==Starting applications from within gdb==<br />
<br />
To start an application with gdb you can start gdb as follows:<br />
<br />
> gdb kedit<br />
GNU gdb 4.95.0<br />
Copyright 2000 Free Software Foundation, Inc.<br />
GDB is free software, covered by the GNU General Public License, and you are<br />
welcome to change it and/or distribute copies of it under certain conditions.<br />
Type "show copying" to see the conditions.<br />
There is absolutely no warranty for GDB. Type "show warranty" for details.<br />
This GDB was configured as "i686-pc-linux-gnu"...<br />
(gdb)<br />
<br />
You can now set the command line arguments that you want to pass to kedit with<br />
the gdb command "<tt>set args</tt>":<br />
<br />
(gdb) set args myfile.txt<br />
(gdb)<br />
<br />
gdb has loaded the kedit executable on startup but it hasn't loaded any of<br />
the libraries yet. This means that you can't set any breakpoints in the<br />
libraries yet. The easiest way to do that is to set a breakpoint in the<br />
first line of main and then start the program:<br />
<br />
(gdb) break main<br />
Breakpoint 1 at 0x804855c<br />
(gdb) run<br />
Starting program: /ext/kde2.0/bin/kedit myfile.txt<br />
Breakpoint 1 at 0x4002cf18: file kedit.cpp, line 1595.<br />
<br />
Breakpoint 1, main (argc=2, argv=0xbffff814) at kedit.cpp:1595<br />
1595 bool have_top_window = false;<br />
Current language: auto; currently c++<br />
(gdb)<br />
<br />
You can now set breakpoints everywhere. For example lets set a breakpoint<br />
in the KApplication constructor. Unfortunately, gdb is not very good in<br />
handling C++ names, so it is not really possible to specify the constructor<br />
directly after the break command. Instead we look up a line of source<br />
code where we want to place the breakpoint. An external editor is of great<br />
use at this point. With the list command we can select the source file we<br />
are interested in and verify that we have found the correct source line:<br />
<br />
(gdb) list kapp.cpp:220<br />
215 parseCommandLine( argc, argv );<br />
216 }<br />
217<br />
218 KApplication::KApplication( bool allowStyles, bool GUIenabled ) :<br />
219 QApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),<br />
220 GUIenabled ),<br />
221 KInstance( KCmdLineArgs::about),<br />
222 d (new KApplicationPrivate)<br />
223 {<br />
224 if (!GUIenabled)<br />
(gdb) break 224<br />
Breakpoint 2 at 0x4048aa7e: file kapp.cpp, line 224.<br />
(gdb)<br />
<br />
We can now continue the execution of kedit. Execution will stop when it hits<br />
a breakpoint or when the program exits. In this case execution will stop<br />
in the first line of the KApplication constructor:<br />
<br />
(gdb) continue<br />
Continuing.<br />
Qt: gdb: -nograb added to command-line options.<br />
Use the -dograb option to enforce grabbing.<br />
<br />
Breakpoint 2, KApplication::KApplication (this=0xbffff6a8, allowStyles=true,<br />
GUIenabled=true) at kapp.cpp:224<br />
224 if (!GUIenabled)<br />
(gdb)<br />
<br />
Important: many applications use "KUniqueApplication" to ensure that only one instance can exist at a given time in a given KDE session. This is the case for kwin, kontact, konsole, plasma, etc. To debug those applications, attach to them while they're running (see next session) or use <code>set args --nofork</code><br />
<br />
==Attaching gdb to already running applications==<br />
<br />
Sometimes it is not practical to start an application from within gdb.<br />
E.g. in those cases where you didn't know the application was about to<br />
crash :-) When you get the friendly DrKonqi dialog informing you about<br />
a crash you are just in time to start your debugger.<br />
<br />
First lets attach gdb to an application that hasn't crashed (yet).<br />
<br />
You start with finding the process of the application with e.g. "ps -aux":<br />
<br />
> ps -aux | grep kedit<br />
bastian 21570 15.1 6.8 13740 8800 pts/6 S 15:34 0:01 kedit<br />
bastian 21582 0.0 0.3 1132 412 pts/6 R 15:34 0:00 grep kedit<br />
<br />
From this you learn that kedit has process id 21570. Now you can start gdb as<br />
follows:<br />
<br />
> gdb kedit 21570<br />
GNU gdb 4.95.0<br />
Copyright 2000 Free Software Foundation, Inc.<br />
GDB is free software, covered by the GNU General Public License, and you are<br />
welcome to change it and/or distribute copies of it under certain conditions.<br />
Type "show copying" to see the conditions.<br />
There is absolutely no warranty for GDB. Type "show warranty" for details.<br />
This GDB was configured as "i686-pc-linux-gnu"...<br />
/home1/bastian/21570: No such file or directory.<br />
Attaching to program: /ext/kde2.0/bin/kedit, Pid 21570<br />
Reading symbols from /ext/kde2.0/lib/kedit.so.0...done.<br />
Loaded symbols for /ext/kde2.0/lib/kedit.so.0<br />
...<br />
Reading symbols from /lib/ld-linux.so.2...done.<br />
Loaded symbols for /lib/ld-linux.so.2<br />
Reading symbols from /lib/libnss_compat.so.2...done.<br />
Loaded symbols for /lib/libnss_compat.so.2<br />
Reading symbols from /lib/libnsl.so.1...done.<br />
Loaded symbols for /lib/libnsl.so.1<br />
0x40c3d88e in __select () from /lib/libc.so.6<br />
(gdb)<br />
<br />
You will usually end up in the middle of a select() call from the event-loop.<br />
This is the place where a KDE application spends most of its time, waiting<br />
for things to happen.<br />
<br />
A backtrace will typically look something like this:<br />
<br />
(gdb) bt<br />
#0 0x40c3d88e in __select () from /lib/libc.so.6<br />
#1 0x40a22844 in __DTOR_END__ () at fam.c++:356<br />
#2 0x407293bf in QApplication::enter_loop (this=0xbffff6e8)<br />
at kernel/qapplication.cpp:2552<br />
#3 0x406b1d7b in QApplication::exec (this=0xbffff6e8)<br />
at kernel/qapplication_x11.cpp:2217<br />
#4 0x4002d500 in main (argc=1, argv=0xbffff854) at kedit.cpp:1662<br />
#5 0x40bbba5e in __libc_start_main (main=0x8048568 &lt;main&gt;, argc=1,<br />
argv=0xbffff854, init=0x8048514 &lt;_init&gt;, fini=0x80486cc &lt;_fini&gt;,<br />
rtld_fini=0x4000aa20 &lt;_dl_fini&gt;, stack_end=0xbffff84c)<br />
at ../sysdeps/generic/libc-start.c:92<br />
(gdb)<br />
<br />
==Debugging core files with GDB==<br />
<br />
Debugging process requires much memory. If you have to inspect crash, you can debug core files. It's much faster and requires less memory. First limit the maximum size of core files and run the application:<br />
ulimit -c 100000<br />
kedit --nocrashhandler<br />
Don't forget to use '--nocrashhandler' option. Core file would be created if the application crashed, so you can use gdb with created core file:<br />
gdb kedit ./core-file #in my system it is core.PID<br />
<br />
==Improving your gdb experience for KDE/Qt applications==<br />
<br />
In the SVN path named "kdesdk", you will find the file [http://websvn.kde.org/trunk/KDE/kdesdk/scripts/kde-devel-gdb kdesdk/scripts/kde-devel-gdb].<br />
This file contains a few macros that help looking into some Qt objects (for instance QString).<br />
See the beginning of the file for instructions on how to use it.<br />
<br />
If you want to go even further, you can apply those [http://developer.kde.org/documentation/other/gdb-patches patches to the gdb source],<br />
to fix a few annoyancies in gdb:<br />
<br />
* source.c: don't try to open a directory in "." that has the same name as the executable we want to open (not needed for gdb-6.0 and above)<br />
* symfile.c: no prompting at end of page while opening shared libraries (not needed for gdb-6.2 and above)<br />
* solib.c: less output when opening shared libraries<br />
<br />
Those patches are maintained by [mailto:faure@kde.org David Faure].<br />
<br />
Have fun with gdb! Hmm, ok, the definition of 'fun' is very relative...</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Debugging/Debugging_with_GDB&diff=28595Development/Tutorials/Debugging/Debugging with GDB2008-06-20T13:38:50Z<p>Powerfox: Added debugging core files section</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Debugging/Debugging with GDB}}<br />
This is a short tutorial on debugging KDE applications. Throughout this<br />
tutorial I will use "kedit" as an example application.<br />
<br />
==Debugging with GDB==<br />
<br />
The recommended version of gdb to use is version 4.95 or higher; older<br />
versions have problems generating proper backtraces.<br />
<br />
There are three ways to debug an application with gdb:<br />
<br />
# You can start the application from within gdb.<br />
# You can attach gdb to an already running application.<br />
# You can run gdb after an application has crashed using a core file.<br />
<br />
==Starting applications from within gdb==<br />
<br />
To start an application with gdb you can start gdb as follows:<br />
<br />
> gdb kedit<br />
GNU gdb 4.95.0<br />
Copyright 2000 Free Software Foundation, Inc.<br />
GDB is free software, covered by the GNU General Public License, and you are<br />
welcome to change it and/or distribute copies of it under certain conditions.<br />
Type "show copying" to see the conditions.<br />
There is absolutely no warranty for GDB. Type "show warranty" for details.<br />
This GDB was configured as "i686-pc-linux-gnu"...<br />
(gdb)<br />
<br />
You can now set the command line arguments that you want to pass to kedit with<br />
the gdb command "<tt>set args</tt>":<br />
<br />
(gdb) set args myfile.txt<br />
(gdb)<br />
<br />
gdb has loaded the kedit executable on startup but it hasn't loaded any of<br />
the libraries yet. This means that you can't set any breakpoints in the<br />
libraries yet. The easiest way to do that is to set a breakpoint in the<br />
first line of main and then start the program:<br />
<br />
(gdb) break main<br />
Breakpoint 1 at 0x804855c<br />
(gdb) run<br />
Starting program: /ext/kde2.0/bin/kedit myfile.txt<br />
Breakpoint 1 at 0x4002cf18: file kedit.cpp, line 1595.<br />
<br />
Breakpoint 1, main (argc=2, argv=0xbffff814) at kedit.cpp:1595<br />
1595 bool have_top_window = false;<br />
Current language: auto; currently c++<br />
(gdb)<br />
<br />
You can now set breakpoints everywhere. For example lets set a breakpoint<br />
in the KApplication constructor. Unfortunately, gdb is not very good in<br />
handling C++ names, so it is not really possible to specify the constructor<br />
directly after the break command. Instead we look up a line of source<br />
code where we want to place the breakpoint. An external editor is of great<br />
use at this point. With the list command we can select the source file we<br />
are interested in and verify that we have found the correct source line:<br />
<br />
(gdb) list kapp.cpp:220<br />
215 parseCommandLine( argc, argv );<br />
216 }<br />
217<br />
218 KApplication::KApplication( bool allowStyles, bool GUIenabled ) :<br />
219 QApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),<br />
220 GUIenabled ),<br />
221 KInstance( KCmdLineArgs::about),<br />
222 d (new KApplicationPrivate)<br />
223 {<br />
224 if (!GUIenabled)<br />
(gdb) break 224<br />
Breakpoint 2 at 0x4048aa7e: file kapp.cpp, line 224.<br />
(gdb)<br />
<br />
We can now continue the execution of kedit. Execution will stop when it hits<br />
a breakpoint or when the program exits. In this case execution will stop<br />
in the first line of the KApplication constructor:<br />
<br />
(gdb) continue<br />
Continuing.<br />
Qt: gdb: -nograb added to command-line options.<br />
Use the -dograb option to enforce grabbing.<br />
<br />
Breakpoint 2, KApplication::KApplication (this=0xbffff6a8, allowStyles=true,<br />
GUIenabled=true) at kapp.cpp:224<br />
224 if (!GUIenabled)<br />
(gdb)<br />
<br />
Important: many applications use "KUniqueApplication" to ensure that only one instance can exist at a given time in a given KDE session. This is the case for kwin, kontact, konsole, plasma, etc. To debug those applications, attach to them while they're running (see next session) or use <code>set args --nofork</code><br />
<br />
==Attaching gdb to already running applications==<br />
<br />
Sometimes it is not practical to start an application from within gdb.<br />
E.g. in those cases where you didn't know the application was about to<br />
crash :-) When you get the friendly DrKonqi dialog informing you about<br />
a crash you are just in time to start your debugger.<br />
<br />
First lets attach gdb to an application that hasn't crashed (yet).<br />
<br />
You start with finding the process of the application with e.g. "ps -aux":<br />
<br />
> ps -aux | grep kedit<br />
bastian 21570 15.1 6.8 13740 8800 pts/6 S 15:34 0:01 kedit<br />
bastian 21582 0.0 0.3 1132 412 pts/6 R 15:34 0:00 grep kedit<br />
<br />
From this you learn that kedit has process id 21570. Now you can start gdb as<br />
follows:<br />
<br />
> gdb kedit 21570<br />
GNU gdb 4.95.0<br />
Copyright 2000 Free Software Foundation, Inc.<br />
GDB is free software, covered by the GNU General Public License, and you are<br />
welcome to change it and/or distribute copies of it under certain conditions.<br />
Type "show copying" to see the conditions.<br />
There is absolutely no warranty for GDB. Type "show warranty" for details.<br />
This GDB was configured as "i686-pc-linux-gnu"...<br />
/home1/bastian/21570: No such file or directory.<br />
Attaching to program: /ext/kde2.0/bin/kedit, Pid 21570<br />
Reading symbols from /ext/kde2.0/lib/kedit.so.0...done.<br />
Loaded symbols for /ext/kde2.0/lib/kedit.so.0<br />
...<br />
Reading symbols from /lib/ld-linux.so.2...done.<br />
Loaded symbols for /lib/ld-linux.so.2<br />
Reading symbols from /lib/libnss_compat.so.2...done.<br />
Loaded symbols for /lib/libnss_compat.so.2<br />
Reading symbols from /lib/libnsl.so.1...done.<br />
Loaded symbols for /lib/libnsl.so.1<br />
0x40c3d88e in __select () from /lib/libc.so.6<br />
(gdb)<br />
<br />
You will usually end up in the middle of a select() call from the event-loop.<br />
This is the place where a KDE application spends most of its time, waiting<br />
for things to happen.<br />
<br />
A backtrace will typically look something like this:<br />
<br />
(gdb) bt<br />
#0 0x40c3d88e in __select () from /lib/libc.so.6<br />
#1 0x40a22844 in __DTOR_END__ () at fam.c++:356<br />
#2 0x407293bf in QApplication::enter_loop (this=0xbffff6e8)<br />
at kernel/qapplication.cpp:2552<br />
#3 0x406b1d7b in QApplication::exec (this=0xbffff6e8)<br />
at kernel/qapplication_x11.cpp:2217<br />
#4 0x4002d500 in main (argc=1, argv=0xbffff854) at kedit.cpp:1662<br />
#5 0x40bbba5e in __libc_start_main (main=0x8048568 &lt;main&gt;, argc=1,<br />
argv=0xbffff854, init=0x8048514 &lt;_init&gt;, fini=0x80486cc &lt;_fini&gt;,<br />
rtld_fini=0x4000aa20 &lt;_dl_fini&gt;, stack_end=0xbffff84c)<br />
at ../sysdeps/generic/libc-start.c:92<br />
(gdb)<br />
<br />
==Debugging core files with GDB==<br />
<br />
Debugging process requires much memory. If you have to inspect crash, you can debug core files. It's much faster and requires less memory. First limit the maximum size of core files and run the application:<br />
ulimit -c 100000<br />
kdevelop --nocrashhandler<br />
Don't forget to use '--nocrashhandler' option. Core file would be created if the application crashed, so you can use gdb with created core file:<br />
gdb kedit ./core-file #in my system it is core.PID <br />
<br />
==Improving your gdb experience for KDE/Qt applications==<br />
<br />
In the SVN path named "kdesdk", you will find the file [http://websvn.kde.org/trunk/KDE/kdesdk/scripts/kde-devel-gdb kdesdk/scripts/kde-devel-gdb].<br />
This file contains a few macros that help looking into some Qt objects (for instance QString).<br />
See the beginning of the file for instructions on how to use it.<br />
<br />
If you want to go even further, you can apply those [http://developer.kde.org/documentation/other/gdb-patches patches to the gdb source],<br />
to fix a few annoyancies in gdb:<br />
<br />
* source.c: don't try to open a directory in "." that has the same name as the executable we want to open (not needed for gdb-6.0 and above)<br />
* symfile.c: no prompting at end of page while opening shared libraries (not needed for gdb-6.2 and above)<br />
* solib.c: less output when opening shared libraries<br />
<br />
Those patches are maintained by [mailto:faure@kde.org David Faure].<br />
<br />
Have fun with gdb! Hmm, ok, the definition of 'fun' is very relative...</div>Powerfoxhttps://techbase.kde.org/index.php?title=Talk:Broken/Archive%5Cx3aDevelopment/Tutorials/Git&diff=25819Talk:Broken/Archive\x3aDevelopment/Tutorials/Git2008-05-10T12:04:47Z<p>Powerfox: Link</p>
<hr />
<div>Lots of good ideas can be found here; [http://wiki.winehq.org/GitWine Git tutorial at WineHq].<br />
I am in the process of writing a front-end that is more userfriendly; it may be useful to link to it [http://vng.googlecode.com home] [http://repo.or.cz/w/vng.git repo].<br />
[[User:Zander|Zander]] 09:51, 21 April 2008 (CEST)<br />
<br />
A little article about Git + KDevplatform: http://www.kdevelop.org/mediawiki/index.php/Using_Git<br />
It covers svn:externals. May I add it to the article?<br />
[[User:powerfox|powerfox]] 16:04, 10 May 2008</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4/Kubuntu_and_Debian_(ru)&diff=19654Getting Started/Build/KDE4/Kubuntu and Debian (ru)2008-01-12T20:19:22Z<p>Powerfox: From Build</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4/Kubuntu and Debian}}<br />
<br />
Здесь приведено уточнение всех зависимостей, которые должны быть удовлетворены в Kubuntu 7.10 (Gutsy) и Debian (Testing/Unstable), чтобы получить минимальное работающее окружение. Их можно установить с помощью команды, приведённой ниже:<br />
<code bash><br />
sudo aptitude install build-essential cdbs debhelper cmake \<br />
kdesdk-scripts subversion ssh xserver-xephyr doxygen libqt4-dev dbus-x11 \<br />
libstreamanalyzer-dev libstrigiqtdbusclient-dev \<br />
libxml2-dev libxslt1-dev shared-mime-info libungif4-dev libssl-dev \<br />
libboost-dev libgpgme11-dev libxine-dev libqimageblitz-dev<br />
</code><br />
<br />
Будут установлены некоторые необходимые для любой сборки пакеты (такие как build essential) и будут удовлетворены все зависимости, выполнение которых необходимо для сборки KDE 4, и установлены некоторые рекомендованные пакеты (например, libssl-dev для поддержки https). Soprano, рекомендованный к установке, следует [[#Install soprano from svn|устанавливать из svn]]. Остальные необязательные и рекомендованные пакеты перечислены ниже.<br />
<br />
После установки всех требуемых пакетов вернитесь к <br />
[[Getting_Started/Build/KDE4#kdelibs|сборке KDE 4]].<br />
<br />
<br />
== Необходимое для сборки программное обеспечение ==<br />
<br />
В Kubuntu 7.04 (Feisty) и Debian (Testing/Unstable) необходимое программное обеспечение можно установить следующей командой:<br />
<code><br />
sudo aptitude install build-essential cdbs debhelper cmake \<br />
libxml2-dev libxslt1-dev libbz2-dev libclucene-dev librdf-dev \<br />
shared-mime-info libgl1-mesa-dev libglu1-mesa-dev mesa-common-dev \<br />
libxext-dev libjpeg-dev libpng12-dev subversion libsm-dev libxinerama-dev \<br />
libxrender-dev libfontconfig-dev libboost-dev libxcursor-dev doxygen \<br />
libungif4-dev libdbus-1-dev libssl-dev libgpgme11-dev \<br />
libasound2-dev kdesdk-scripts libpth-dev libjasper-dev \<br />
ssh libxine-dev libqimageblitz-dev libqimageblitz4 libglib2.0-dev \<br />
libxkbfile-dev libenchant-dev libbluetooth-dev network-manager-dev \<br />
libsmbclient-dev libxcb1-dev libcaptury-dev libxcomposite-dev \<br />
libxdamage-dev libusb-dev libgpgme11-dev libldap2-dev<br />
</code><br />
<br />
В Kubuntu 7.10 (Gutsy) и Debian unstable следует добавить:<br />
<code><br />
sudo aptitude install dbus-x11 libqt4-dev libqca2-dev libeigen-dev \<br />
libstreamanalyzer-dev libsoprano-dev libstrigiqtdbusclient-dev \<br />
libxklavier11-dev libxml2-utils libdbus-1-dev libxslt1-dev cmake libbz2-dev \<br />
libungif4-dev libgpgme11-dev libboost-dev libxine-dev libxkbfile-dev<br />
</code><br />
<br />
Для того чтобы задействовать всю функциональность системы документации (API documentation framework), также выполните:<br />
<code><br />
sudo aptitude install graphviz<br />
</code><br />
<br />
В Kubuntu Gutsy и Debian unstable нет никакой необходимости компилировать qt или kdesupport. Все необходимые пакеты доступны после процедуры описанной в настоящем разделе, потому переходите сразу к [[#kdelibs|сборке kdelibs]], перед этим только [[#Создание пользователя для разработки KDE 4|создав отдельного пользователя в системе для запуска программ KDE4]].<br />
<br />
{{Note|При возникновении проблем при компиляции KDE4 Beta4 или выше в Kubuntu 7.10, похожих на:<br />
<br />
Soprano version is too low<br />
<br />
strigi xxx.h not found...<br />
<br />
Необходимо обновить и собрать соответствующую часть исходного кода kdesupport.<br />
Это описано в разделе о сборке kdesupport.<br />
<br />
Также удалите пакет soprano: sudo apt-get remove libsoprano4 libsoprano-dev (этот пакет мы соберём из исходников самостоятельно)<br />
<br />
If you still get an error in the kdelibs section about soprano like:<br />
CMake Error: Error in cmake code at<br />
$src/KDE/kdelibs/cmake/modules/FindSoprano.cmake:78:<br />
FILE Internal CMake error when trying to open file: /usr/include/soprano/version.h for reading.<br />
<br />
then delete kdelibs/CMakeCache.txt<br />
}}</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4/Mandriva_(ru)&diff=19651Getting Started/Build/KDE4/Mandriva (ru)2008-01-12T19:57:32Z<p>Powerfox: From Build</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4/Mandriva}}<br />
<br />
В Mandriva необходимые для сборки пакеты устанавливаются с помощью:<br />
<code bash><br />
urpmi gcc-c++ cmake libxml2-devel libbzip2_1-devel \<br />
libclucene0-devel liblrdf2-devel libmesagl1-devel \<br />
subversion doxygen libdbus-1_3-devel libopenssl0.9.8-devel \<br />
libalsa2-devel libgpgme-devel libboost1-devel<br />
</code><br />
<br />
При использовании 64-х битной сборки необходимо заменить все префиксы "lib..." на "lib64...".<br />
<br />
Если Вы предпочитаете использовать графический интерфейс, то выберите перечисленные выше пакеты в утилите "Install Software" из Mandriva Linux Control Center.<br />
<br />
После этого CMake и DBus будут установлены - пункты 5 и 6 можно пропустить.</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4/Gentoo_(ru)&diff=19649Getting Started/Build/KDE4/Gentoo (ru)2008-01-12T19:52:43Z<p>Powerfox: From Build</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4/Gentoo}}<br />
<br />
==== Ручная установка ====<br />
Используя стабильные сборочные файлы (ebuilds), не забудьте обновить дерево портежей («синькнуться»), прежде чем приступить к установке.<br />
<br />
Нам нужно разрешить следующие сборочные файлы, замаскированные ключами:<br />
<code bash><br />
echo 'dev-util/cmake' >> /etc/portage/package.keywords<br />
echo 'dev-cpp/clucene' >> /etc/portage/package.keywords<br />
</code><br />
<br />
<br />
Удостоверьтесь, что для redland установлен USE-флаг berkdb, в противном случае nepomuk не будет работать.<br />
<code bash><br />
# echo 'dev-libs/redland berkdb' >> /etc/portage/package.use<br />
</code><br />
<br />
Далее приведён список необходимых пакетов, некоторые из которых могут быть уже установлены (их можно пропустить, добавив флаг обновления в emerge).<br />
<br />
<code bash><br />
emerge -avu 'sys-devel/gcc' \<br />
'dev-util/subversion' \<br />
'dev-util/pkgconfig' \<br />
'x11-base/xorg-x11' \<br />
'virtual/glut' \<br />
'media-libs/mesa' \<br />
'media-libs/jpeg' \<br />
'media-libs/libpng' \<br />
'media-libs/giflib' \<br />
'dev-cpp/clucene' \<br />
'dev-util/cppunit' \<br />
'media-libs/liblrdf' \<br />
'dev-libs/libxml2' \<br />
'dev-libs/libxslt' \<br />
'x11-misc/shared-mime-info' \<br />
'dev-libs/boost' \<br />
'dev-util/cmake' \<br />
'dev-libs/redland' \<br />
'sys-apps/dbus' \<br />
'sys-apps/hal' \<br />
'x11-libs/qt'<br />
</code><br />
<br />
<br />
Также может потребоваться выполнить emerge либо для 'kde-base/kdesdk', либо для kde-base/kdesdk-scripts'. <br />
<br />
<br />
Если вы установили DBUS, CMAKE, QT и (возможно) HAL, то соответствующие секции можно пропустить.<br />
<br />
Удачи!<br />
<br />
==== Установка с помощью portage ====<br />
Также пакеты KDE 4 можно установить напрямую с помощью<br />
<code bash><br />
emerge -a <packagename><br />
</code><br />
<br />
Получите всё необходимое на [http://gentoo-wiki.com/TIP_Overlays#Layman install layman] и положите в оверлей "kde" (содержащий экспериментальные сборочные файлы)<br />
<code bash><br />
layman -a kde<br />
</code><br />
После этого следует настроить USE-флаги, необходимые для KDE 4, и задать portage использование тестовых (экспериментальных) сборочных файлов вместо стабильных для KDE 3.<br />
<br />
Таким образом, система портежей отследит все зависимости.<br />
<br />
Подробная инструкция по сборке KDE 4 в Gentoo находится в статье [http://overlays.gentoo.org/proj/kde/wiki KDE overlay wiki]. Обсуждение ebuilds находится в теме о [http://forums.gentoo.org/viewtopic-t-530111-postdays-0-postorder-asc-start-0.html KDE 4 monolithic ebuilds].</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4/Fedora_(ru)&diff=19643Getting Started/Build/KDE4/Fedora (ru)2008-01-12T19:24:16Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4/Fedora}}<br />
Чтобы установить большинство необходимых для сборки KDE4 в Fedora 7 (и выше), выполните:<br />
<br />
<code bash><br />
yum install clucene-core-devel libxml-devel libxslt-devel \<br />
dbus-devel boost-devel bzip2-devel openssl-devel alsa-lib-devel \<br />
redland-devel rasqal-devel raptor-devel hspell-devel aspell-devel \<br />
cups-devel xine-lib-devel avahi-devel gamin-devel OpenEXR-devel \<br />
enchant-devel jasper-devel ilmbase-devel pcre-devel gpgme-devel \<br />
libxklavier-devel glib-devel libusb-devel libsmbclient-devel \<br />
libxcb-devel NetworkManager-devel lm_sensors-devel libraw1394-devel \<br />
bluez-libs-devel gcc-c++ libXext-devel cmake subversion giflib-devel \<br />
libpng-devel libXdamage-devel libXcomposite-devel libXrender-devel \<br />
fontconfig-devel libXft-devel libXcursor-devel libXfixes-devel \<br />
ruby-devel libXScrnSaver-devel libkdcraw-devel exiv2-devel \<br />
lcms-devel libtiff-devel sqlite-devel libxkbfile-devel \<br />
imlib2-devel patch gstreamer-plugins-base-devel gsl-devel<br />
</code><br />
<br />
После этого CMake и DBus будут установлены - пункты 5 и 6 можно пропустить.<br />
<br />
DCH-10/15/07: Примечание: возможно, что проще собрать RPM-ки. Можно отредактировать переменные в /etc/rpm/macros.kde4 (which is provided by Rawhide kde-filesystem).<br />
<br />
Секция сборки (build stage) должна выглядеть примерно так:<br />
<br />
%build<br />
<br />
mkdir -p %{_target_platform}<br />
<br />
pushd %{_target_platform}<br />
<br />
%{cmake_kde4} ..<br />
<br />
popd<br />
<br />
make %{?_smp_mflags} -C %{_target_platform}<br />
<br />
Я сумел достичь лучших результатов, собирая kdesupport rpm, что означает, что Вам не потребуется устанавливать RPM-пакеты soprano или strigi. YMMV (непереводимый смайл или восклицание :) ).<br />
<br />
{{TODO| Требуется аудит. Организовать в виде модуля.<br />
}}<br />
<br />
Вернуться к [[Getting_Started/Build/KDE4#HAL|сборке KDE 4]].</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4/Fedora_(ru)&diff=19631Getting Started/Build/KDE4/Fedora (ru)2008-01-12T16:34:20Z<p>Powerfox: From Build</p>
<hr />
<div>Чтобы установить большинство необходимых для сборки KDE4 в Fedora 7 (и выше), выполните:<br />
<br />
<code bash><br />
yum install clucene-core-devel libxml-devel libxslt-devel \<br />
dbus-devel boost-devel bzip2-devel openssl-devel alsa-lib-devel \<br />
redland-devel rasqal-devel raptor-devel hspell-devel aspell-devel \<br />
cups-devel xine-lib-devel avahi-devel gamin-devel OpenEXR-devel \<br />
enchant-devel jasper-devel ilmbase-devel pcre-devel gpgme-devel \<br />
libxklavier-devel glib-devel libusb-devel libsmbclient-devel \<br />
libxcb-devel NetworkManager-devel lm_sensors-devel libraw1394-devel \<br />
bluez-libs-devel gcc-c++ libXext-devel cmake subversion giflib-devel \<br />
libpng-devel libXdamage-devel libXcomposite-devel libXrender-devel \<br />
fontconfig-devel libXft-devel libXcursor-devel libXfixes-devel \<br />
ruby-devel libXScrnSaver-devel libkdcraw-devel exiv2-devel \<br />
lcms-devel libtiff-devel sqlite-devel libxkbfile-devel \<br />
imlib2-devel patch gstreamer-plugins-base-devel gsl-devel<br />
</code><br />
<br />
После этого CMake и DBus будут установлены - пункты 5 и 6 можно пропустить.<br />
<br />
DCH-10/15/07: Примечание: возможно, что проще собрать RPM-ки. Можно отредактировать переменные в /etc/rpm/macros.kde4 (which is provided by Rawhide kde-filesystem).<br />
<br />
Секция сборки (build stage) должна выглядеть примерно так:<br />
<br />
%build<br />
<br />
mkdir -p %{_target_platform}<br />
<br />
pushd %{_target_platform}<br />
<br />
%{cmake_kde4} ..<br />
<br />
popd<br />
<br />
make %{?_smp_mflags} -C %{_target_platform}<br />
<br />
Я сумел достичь лучших результатов, собирая kdesupport rpm, что означает, что Вам не потребуется устанавливать RPM-пакеты soprano или strigi. YMMV (непереводимый смайл или восклицание :) ).<br />
<br />
{{TODO| Требуется аудит. Организовать в виде модуля.<br />
}}<br />
<br />
Вернуться к [[Getting_Started/Build/KDE4#HAL|сборке KDE 4]].</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4&diff=19616Getting Started/Build/KDE42008-01-12T14:49:07Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Getting Started|<br />
<br />
name=Building KDE4 From Source|<br />
<br />
pre=[[../../Sources/Anonymous_SVN|Anonymous SVN Quickstart Guide]]|<br />
<br />
next=[[../../Set_up_KDE_4_for_development|Set up KDE 4 for development]]|<br />
<br />
reading=[[../kdesvn-build|kdesvn-build: The KDE From Subversion Build Tool]]<br>[[../../Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br>[[Development/Tutorials/CMake |Introduction to CMake]]<br>[[../KDE4/FreeBSD|FreeBSD notes]]<br>[[../KDE4/Mac OS X|Instructions for Mac OS X]]<br>[[../KDE4/Windows|Instructions for MS Windows]]|<br />
}}<br />
<br />
== Abstract ==<br />
<br />
This tutorial shows one way to get KDE from trunk running on Linux/BSD systems. There are also tutorials for [[Getting_Started/Build/KDE4/FreeBSD|FreeBSD]], [http://www.kdelibs.com/ Windows], [[Getting_Started/Build/KDE4/Mac OS X|Mac OS X]] and [http://solaris.kde.org/ Solaris]. Throughout the tutorial the bash shell is used.<br />
<br />
{{warning|Expect a higher risk of build failure '''on Mondays''' when most kdelibs changes are committed. [http://developer.kde.org/~dirk/dashboard/ Dashboard] reports unexpected breakages. You are encouraged to fix failing modules.<br />
}}<br />
<br />
== Software Requirements ==<br />
<br />
The following needs to be installed to successfully use this tutorial:<br />
* gcc and g++, preferably version 4.2 or higher<br />
* svn, the subversion revision control client<br />
* pkg-config<br />
* development libraries and headers for X11, OpenGL (mesa-common-dev and libglu1-mesa-dev), libjpeg, libpng, libungif, [http://clucene.sourceforge.net/index.php/Downloads libclucene], [http://download.librdf.org/source/ librdf], libxml2 and libxslt<br />
* the <tt>makeobj</tt> script, which is included in kdesdk. You can install it from kdesdk (kdesdk-scripts on Debian) or similar packages, or download at [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/makeobj WebSVN]<br />
* the [http://freedesktop.org/wiki/Software/shared-mime-info shared-mime-info package], is the freedesktop MIME standard now used in KDE<br />
* [http://boost.org/ boost], used by kdebase; after build and/or install, in order to make cmake aware about its location (FindBoost), add the boost directory (which contains the include subdirectory) to CMAKE_INCLUDE_PATH or set a environment variable called BOOST_ROOT that points to the boost directory.<br />
<br />
<br />
== Create a user account for KDE4 development ==<br />
<br />
{{Note|<br />
Some people like to have a separate user account for KDE 4 (for instance an old bug deleted files by mistake), and the instructions below were written with that approach.<br />
<br />
However it is much more efficient to do everything with a single user account, see [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br />
for more details. <br />
<br />
You can still follow the instructions below, but don't put the environment variables in your <tt>.bashrc</tt>, put them in a separate file that you source to switch to the KDE 4 environment.<br />
}}<br />
<br />
<br />
=== Option 1: Command Line ===<br />
{{Note|<br />
On some systems a new user is configured by default to use {{path|/bin/sh}}. Using {{path|/bin/sh}} can be very inconvenient to work with and you may want to change it to {{path|/bin/bash}} or another shell.<br />
On Ark Linux and Fedora, you can skip the <tt>-s /bin/bash</tt> switch - {{path|/bin/sh}} is {{path|bash}}.<br />
}}<br />
<code bash><br />
useradd -m kde-devel -s /bin/bash<br />
passwd kde-devel<br />
</code><br />
<br />
<br />
{{Warning|<br />
The new kde-devel user will not be added automatically to all the user groups, which will result in not having sound, not being able to sudo, etc. Edit your /etc/groups file to add the kde-devel user to all the groups that you need (probably the groups that your usual username is already assigned to).<br />
}}<br />
<br />
=== Option 2: Using KControl ===<br />
<br />
Instead of using the commands above, you can also use the User module in the KDE Control Center if you already have KDE3 installed.<br />
<br />
=== Setting up the environment ===<br />
<br />
Copy the {{path|~/.bashrc}} from your normal user account to the new kde-devel account. Next, copy and paste the contents of the [[Getting Started/Increased Productivity in KDE4 with Scripts/.bashrc|example .bashrc]] into {{path|~kde-devel/.bashrc}}. Be sure to comment out the line <tt>alias make=makeobj</tt> if you do not have the <tt>[[Getting Started/Build/KDE4#Required Software|makeobj]]</tt> command available. You will probably also want to modify the path to make sure it doesn't include your kde3 paths. Also if you want to use KDevelop to develop KDE 4 applications you may pass the ''-GKDevelop3'' flag to the ''cmake'' command (to make CMake generate KDevelop project files, it will help to avoid rebuilding in the future, see [[Getting_Started/Set_up_KDE_4_for_development#Setting_up_the_environment|this]]). <br />
To make it run, you have to open a new bash or to execute <br />
<code bash><br />
source ~/.bashrc<br />
</code><br />
<br />
This will provide access to commands such as <tt>cmakekde</tt> that are used in this tutorial as well as ensure that the proper paths are in place for Qt, KDE and CMake binaries.<br />
<br />
For more information, please read the [[Getting Started/Increased Productivity in KDE4 with Scripts]] tutorial.<br />
<br />
=== Switching to the New User ===<br />
Switch to the user kde-devel: (don't forget the dash)<br />
<code bash><br />
ssh -X kde-devel@localhost<br />
</code><br />
<br />
{{Note|<br />
If the ssh command fails, check out the [[Getting_Started/Set_up_KDE_4_for_development#Launching_KDE_4_apps|Launching KDE 4 apps]] section of the [[Getting_Started/Set_up_KDE_4_for_development|KDE4 development guide]].<br />
}}<br />
<br />
== Required packages from your distribution ==<br />
The requirements to build kde4 from source vary from distribution to distribution. Instructions for your distribution are provided below:<br />
<br />
* [[/Ark Linux|Ark Linux]]<br />
* [[/Arch Linux|Arch Linux]]<br />
* [[/Fedora|Fedora]]<br />
* [[/Kubuntu and Debian|Kubuntu and Debian]]<br />
* [[/openSUSE|openSUSE]]<br />
* [[/Gentoo|Gentoo]]<br />
* [[/Mandriva|Mandriva]]<br />
<br />
Your next compilation step depends on the packages supplied by your distro.<br />
<br />
== D-Bus ==<br />
QtDBus and KDE are known to work with D-Bus versions 0.62, as well as 0.92 and upwards. Versions 0.60 and 0.61 may work too but are not tested. Versions 0.90 and 0.91 are known not to work. We recommend using post-1.0 release versions (at least 0.94), so consider upgrading if you haven't done so.<br />
<br />
You may skip this section if you have a recent D-Bus version or if you don't want to upgrade. You probably want to skip building the bindings until/unless you know you will be building HAL (see below).<br />
<br />
Before running these steps in the recipe, make sure your X11 headers and libraries are available. The configure script run on line 5 of the following instructions should output:<br />
Building X11 code: yes<br />
<br />
=== The Recipe ===<br />
<br />
{{tip|Make sure you did set up your environment correctly as described [[Getting_Started/Build/KDE4#Setting_up_the_environment|above]]. This is necessary for the <tt>cs</tt> and <tt>cb</tt> functions to work.}}<br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]] <br />
wget http://dbus.freedesktop.org/releases/dbus/dbus-1.0.2.tar.gz<br />
tar -xvzf dbus-1.0.2.tar.gz<br />
cd dbus-1.0.2/<br />
./configure --prefix=$DBUSDIR --localstatedir=/var<br />
make<br />
sudo make install<br />
sudo dbus-uuidgen --ensure<br />
<br />
cs # see above<br />
wget http://dbus.freedesktop.org/releases/dbus-glib/dbus-glib-0.74.tar.gz<br />
tar -xvzf dbus-glib-0.74.tar.gz<br />
cd dbus-glib-0.74/<br />
./configure --prefix=$DBUSDIR<br />
make<br />
sudo make install<br />
cd<br />
sudo chown -R kde-devel:kde-devel *<br />
<br />
=== What's Happening === <br />
After changing into the source directory (line 1), D-Bus source code is downloaded from freedesktop.org (line 2) and unpacked (line 3). After going into the newly created D-Bus directory (line 4), the build is set up using the supplied {{path|configure}} script (line 5). After building (line 6) and installing (line 7) D-Bus, we use the <tt>dbus-uuidgen</tt> tool to install a machine identification file that allows the bus to start automatically when the desktop session starts (line 8).<br />
<br />
Note that you need write access to {{path|/var}} for the last two steps. If your system does not have the sudo command, you can use the <tt>su</tt> command instead, e.g. <tt>su -c "make install"</tt>.<br />
<br />
The steps for building the glib bindings are similar to the above.<br />
<br />
When these two packages are done building, we must fix the file ownership because 'sudo make install' has created root owned files and directories in ~kde-devel/kde.<br />
<br />
== CMake ==<br />
Skip this if you have [http://cmake.org/ CMake] >=2.4.5 installed. <br />
You should be able to directly use the binary packages available on the [http://www.cmake.org/HTML/Download.html CMake site]. There are also distribution specific packages available.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click Here to learn more]] <br />
wget http://www.cmake.org/files/v2.4/cmake-2.4.6.tar.gz<br />
tar -zxf cmake-2.4.6.tar.gz<br />
mkdir cmake-build<br />
cd cmake-build <br />
../cmake-2.4.6/bootstrap<br />
make<br />
sudo make install<br />
<br />
=== What's Happening ===<br />
First, we go back to the <tt>kde-devel</tt> user's source directory (line 1), get the CMake sources (line 2) and unpack them (line 3). We create a directory to build CMake in (line 4) and go into it (line 5). We then run the CMake bootstrap script to set up the CMake build (line 6), then make (line 7) and install it (line 8) using the root user.<br />
<br />
If your system does not have the <tt>sudo</tt> command, you can instead do <tt>su -c "make install"</tt>.<br />
<br />
== Qt ==<br />
Next we need to get Qt4. KDE is guaranteed to build against any Qt 4.3. Qt 4.2 and earlier are not supported and will not work. <br />
<br />
If your distribution has a recent version of Qt4, that should work. Most distros backport bugfixes, and some distros, like Debian or openSUSE, even use the patches from KDE svn. In other cases, using the recipe below will give you a more stable Qt than your distro. Refer to the distribution specific sections above for more information. <br />
<br />
As for now Qt3 compatibility layer in Qt 4 is mandatory, so please <b>avoid</b> using "-no-qt3support" option when building Qt4 from sources.<br />
<br />
=== The Recipe ===<br />
cd # Note: qt-copy lives in $HOME/qt-copy. See $QTDIR in [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|<font color=red>.bashrc</font>]] <br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/qt-copy<br />
cd qt-copy<br />
./apply_patches<br />
./configure -nomake examples -nomake demos -qt-gif \<br />
-no-exceptions -debug -fast -prefix $QTDIR <br />
make -j2<br />
<br />
# if we don't install, we'll just clear obj files to<br />
# save disk space<br />
if [ $QTDIR = `pwd` ]; then \<br />
find . -name '*.o' -delete ; \<br />
else make install; fi;<br />
<br />
=== What's Happening ===<br />
We switch back to the <tt>kde-devel</tt> user's home directory (line 1) and download the source code using subversion (svn) from KDE's repository (line 2). After changing into the resulting {{path|qt-copy}} directory (line 3), we run a script that manages the patches that come with <tt>qt-copy</tt> (line 4). <br />
<br />
Once the patches have been applied, we then set up the build using the <tt>configure</tt> script (line 5-6). The various command line options used are explained in the {{path|qt-copy/README.qt-copy}} file. Finally, we build the minimal requirements for KDE (line 7) and install (line 10) Qt. If install dir is the same as the current dir (line 8), then we just free some space (line 9) instead. If you want all the example and demo applications, you can either build them individually or simply do a <tt>make</tt> from the {{path|qt-copy}} directory. <br />
<br />
Note that the installation does not require root as it installs Qt locally into {{path|$QTDIR}}. Anyway, installation is only needed if {{path|$QTDIR}} differs from {{path|$HOME/qt-copy}}, which is not the case if you have exactly followed the instructions.<br />
<br />
=== Troubleshooting ===<br />
If you get "error: X11/Xlib.h: No such file or directory", install the devel package of <tt>xorg</tt> (the actual name may vary between operating systems, for example it is <tt>xorg-dev</tt> on Ubuntu based systems such as Kubuntu). <br />
<br />
If you get an error in the configure step about missing defines, check the value of <tt>$QMAKESPEC</tt>. Some distributions set this to point directly to the system-installed Qt. If <tt>unset QMAKESPEC</tt> solves the problem, you probably want to add it to the <tt>~/.bashrc</tt> script.<br />
<br />
If you get an error ".pch/debug-shared/QtCore", this is because Qt-4.3 enables precompiled headers if your gcc supports it, but for some reason it doesn't work for you. If you use distcc, configure qt with -no-pch. If you use icecream, update to the latest icecream from svn trunk.<br />
<br />
Try running any Qt program, like {{program|assistant}}. '''Note:''' You may need to run <tt>xhost +local:kde-devel</tt> as your regular kde3 user to run this application. If it crashes in QSpanData::adjustSpanMethods, then your problem is the oxygen style. Try removing {{path|lib/kde4/plugins/styles/kstyle-oxygen.so}} and {{path|lib/kde4/plugins/styles/oxygen.so}} if they exist in the KDE install prefix.<br />
<br />
== HAL ==<br />
<br />
{{tip|You can use qdbusviewer to see if you have org.freedesktop.hal. If not, you might need a newer version of hal. If you have org.freedesktop.hal, you probably don't need to, and don't ''want'' to, roll your own HAL.}}<br />
<br />
If your system requires you to build a newer version of HAL, there's a decent chance you'll need to build other stuff as well, some of which may not be straight forward. Since this should only be required for older distros, instructions are on [[Getting_Started/Build/HAL| a separate page]].<br />
<br />
== kdesupport ==<br />
<br />
{{warning|Don't forget to read the [[Getting_Started/Build/KDE4#Setting_up_the_environment|Setting Up The Environment]] section first.}}<br />
<br />
There are several libraries that KDE applications rely on in the kdesupport module. This includes Strigi and Soprano for file metadata and search, QImageBlitz for image manipulation needed in kdebase, eigen for visual effects in applications such as Kalzium, taglib for music players and qca for some cryptographic needs. <br />
<br />
Strigi itself has a few dependencies as well: you will need the libraries and headers for libz, libbz2, openssl (libcrypto or libssl), libclucene (>=0.9.16a but watch out: version 0.9.17 does '''not''' work), and either libxml2 or libexpat.<br />
<br />
Please remember that if you use openSUSE, you can install the needed packages from the KDE:KDE4 buildservice repository and do not have to bother with fiddling the details below. Skip to the kdelibs section. <br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/kdesupport/<br />
cd kdesupport<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1). We download the sources in kdesupport using subversion (line 2), go into the new {{path|~/kde/src/kdesupport}} directory (line 3), and commence the build (line 4). This will leave us in the kdesupport build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you get <br />
cmakekde: command not found<br />
then you have to go manually into the kdesupport directory in ~ and execute the command cmakekde. if this still doesn't work, then something is wrong with your bashrc.<br />
<br />
If you get <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 />
LIBXML2_INCLUDE_DIR (ADVANCED)<br />
you should install the development package for libxml2.<br />
<br />
If you get <br />
CMake Error: Could NOT find REDLAND<br />
then you need librdf from the Redland.<br />
If your distribution does not provide the librdf package, you can download the source there: [http://download.librdf.org/source/ http://download.librdf.org/source/] and build it.<br />
(Gentoo users: The ebuild for librdf is named dev-libs/redland)<br />
<br />
If you get<br />
Fetching external item into 'kdesupport/admin'<br />
Error validating server certificate for 'https://...'<br />
see [http://techbase.kde.org/Getting_Started/Sources/Using_Subversion_with_KDE Using Subversion with KDE]<br />
<br />
If you get<br />
FILE cannot create directory: /usr/lib[64]/qt4/plugins/crypto. Maybe need administrative privileges.<br />
<br />
make: *** [install] Error 255<br />
take a second look in the .bashrc file described above, are paths correct? ($QTDIR and $PATH are used to get the QT installation path)<br />
Alternatively, you may see this error if you decided to use a distribution installed version of qt4 and skipped the Qt install above. Either install qt-copy as describe above, or "sudo make install". If you use "sudo make install", make sure that you change the ownership back to your user for some of the ~/kde subdirectories that were effected by using sudo (ie. "<tt>sudo chown -R kde-devel:kde-devel ~/kde</tt>").<br />
<br />
If you get a message related to <br />
target libQtTest.so not found<br />
you may need to recompile qt-copy. This time you should take out<br />
-nomake demos -nomake examples<br />
from the configure command, so that Qt generates library QtTest.<br />
<br />
== kdelibs ==<br />
<br />
We can now move on to building KDE's base libraries.<br />
<br />
=== The Recipe ===<br />
cd <br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
mkdir KDE && cd KDE<br />
svn checkout svn://anonsvn.kde.org/home/kde/branches/KDE/4.0/kdelibs<br />
cd kdelibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1) then make and go into the KDE directory (line 2). We download the sources for kdelibs using subversion (line 3), go into the new {{path|~/kde/src/KDE/kdelibs}} directory (line 4), and commence the build (line 5). This will leave us in the <tt>kdelibs</tt> build directory after the build is completed.<br />
<br />
{{tip|There might be missing dependencies on your system! They are easily overlooked in the output of <tt>cmakekde</tt>.<br />
You might want to do a <tt>cmake $KDE_SRC/KDE/MODULE_NAME</tt> prior to compiling any kde modules (like kdelibs, kdepimlibs etc.)}}<br />
<br />
=== Additional KDE-specific CMake modules ===<br />
There are additional CMake modules in {{path|kdelibs/cmake/modules/}} that are necessary for building KDE4 applications. These will be installed for you when kdelibs itself is installed.<br />
<br />
=== Troubleshooting ===<br />
If you have problems compiling kdelibs, first make sure the software in the [[Getting_Started/Build/KDE4#Software_Requirements|Required Software]] section above is installed and works. Other possible hints include:<br />
* If the <tt>cmakekde</tt> command fails stating that CMake requires an out of source build directory, remove {{path|~/kde/src/KDE/kdelibs/CMakeCache.txt}}, and try again.<br />
<br />
If <tt>cmakekde</tt> still gives the same error then try this <br />
cd<br />
cmake -DCMAKE_INSTALL_PREFIX=$KDEDIR \<br />
-DCMAKE_BUILD_TYPE=debugfull \<br />
-DKDE4_BUILD_TESTS=ON \<br />
~/kde/src/KDE/kdelibs<br />
make<br />
make install<br />
* If you received an error stating "Please create a separate build directory and run 'cmake path_to_kdelibs [options]' there.", then you need to change to your build directory before running cmakekde. (e.g <tt>cs KDE/kdelibs && cb && cmakekde</tt>) If the message stays, run 'svn status' in the kdelibs directory and remove all files labeled with '?'.<br />
* If Qt wasn't found or the wrong version of Qt was found, make sure that the qmake from the Qt you need is the first qmake in the path.<br />
* If qmake wasn't found and you are using Debian packages, /usr/bin/qmake probably points to a wrong qmake version. To fix this run as root:<br />
update-alternatives --config qmake<br />
* If the problems persist, try the CMake make-option <tt>--keep-going</tt>.<br />
* Here you need the libungif library, otherwise you will get an error message like "<tt>Could NOT find GIF</tt>".<br />
* Qt-4.3 upgrade: if you get a link error in kjsembed talking about QScriptEngine, edit CMakeCache.txt in kdelibs and remove the lines that talk about QT_QTUITOOLS_LIBRARY, then type make again (that static library has a new dependency, and the cmake code that adds it needs to run).<br />
* if you get <code>CMake Error: KDE Requires Qt to be built with SSL support<br />
</code>, install openssl-devel, remove CMakeCache.txt and re-compile QT.<br />
* if you get <code>kdelibs/kimgio/ico.cpp:188: undefined reference to `QImage::jumpTable()'</code> it means you compiled QT without QT3 support(no, linking to a true QT3 install won't work)<br />
* if none of the errors above match yours, you might just try a quick'n'dirty <code>make clean</code> in kdelibs.<br />
<br />
== kdepimlibs ==<br />
After <tt>kdelibs</tt>, but before ''kdebase'', you need to build and install ''kdepimlibs''.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/branches/KDE/4.0/kdepimlibs<br />
cd kdepimlibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We go into the KDE source directory (line 1), download the source code for kdepimlibs using subversion (line 2) and then go into the new {{path|~/kde/src/KDE/kdepimlibs}} directory (line 3). We then commence the build (line 4). This will leave us in the <tt>kdepimlibs</tt> build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you have trouble compiling kdepimlibs:<br />
* the cmakekde command may require a later version of the gpgme library. This is available from the project's web site: http://www.gnupg.org/(en)/download/index.html - please note that the build of gpgme also requires libgpg-error, also available from the same location. Both libraries are installed by the "./configure", "make" and "sudo make install" sequence, with the gpgme library configured with the additional "--with-gpg-error-prefix" parameter. You may need to overwrite your existing "/usr/bin/gpgme-config" file with the newer version for the kdepimlibs to pick up the new install.<br />
<br />
== kdebase ==<br />
kdebase is divided into three parts:<br />
* '''apps'''<br />
:This contains applications like Dolphin or KWrite.<br />
* '''runtime'''<br />
:This contains things needed by every application at runtime, like icons. It is a required dependency for each KDE application, so you have to compile and install this.<br />
* '''workspace'''<br />
:This contains things specific to the KDE desktop, like Plasma or the window manager. Most stuff here depends on X11. You only need it if you want to build a full KDE desktop.<br />
<br />
You can build all of kdebase at once, which is described in the recipe below. If you only want to build kdebase-runtime, which is the only requirement, you can replace <code bash>cd kdebase</code> with <code bash>cd kdebase/runtime</code> in the recipe below.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/branches/KDE/4.0/kdebase<br />
cd kdebase<br />
cmakekde<br />
<br />
=== Troubleshooting ===<br />
If you have troubles compiling kdebase:<br />
* Make sure you have the <tt>libxss headers</tt> installed. (Usually you got undefined references on xscreensaver objects if you do not have those headers)<br />
* <tt>which meinproc</tt> has to deliver {{path|/home/kde-devel/kde/bin/meinproc}}<br />
* if cmakekde can not find the path of kdepimlibs, edit the file {{path|$KDE_BUILD/KDE/kdebase/CMakeCache.txt}} and manually set <tt>KDEPIMLIBS_INCLUDE_DIR:PATH=$KDE_BUILD/kdepimlibs</tt><br />
* if you get an error saying "Please set the following variables: X11_XTest_LIB (ADVANCED)", install the devel package of <tt>Xtst</tt>. On some systems, this is packaged separately from <tt>xext</tt> and called <tt>x11proto-xext-dev</tt> or <tt>libxtst-dev</tt>. You may also need to remove the CMakeCache.txt file in the build dir after installing the package.<br />
* the same for "X11_Xinerama_LIB (ADVANCED)" where you will need the devel package for <tt>xinerama</tt>.<br />
* if you get an error complaining about a missing variable X11_Xrandr_LIB, you need the devel package for libxrandr (libxrandr-devel on ubuntu-systems)<br />
* if you get the error "Please set the following variables: FONTCONFIG_INCLUDE_DIR, FONTCONFIG_LIBRARIES (ADVANCED)", then you need to install the libfontconfig headers<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: KMETADATA_LIBRARIES", you need to install soprano from kdesupport and to rebuild kdelibs<br />
* if you get the error "‘XserverRegion’ does not name a type" make sure you have libxcomposite headers installed (<tt>libxcomposite-dev</tt> in ubuntu)<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: QT_QTOPENGL_LIBRARY (ADVANCED) ", try editing CMakeCache.txt and setting QT_QTOPENGL_LIBRARY:FILEPATH=/home/kde-devel/qt-copy/lib/libQtOpenGL.so<br />
<br />
* if you get messages as "KDE4_INSTALL_HANDBOOK() is deprecated. Remove it please. Now all is done in KDE4_CREATE_HANDBOOK." then, either find the files containing the offending line and comment it out manually, or run the following script in ~/kde/src/KDE/kdebase: [http://www.plamadeala.com/files/macros_corrector.sh macros_corrector.sh]. It will just REMOVE the line that has "kde4_create_handbook" in it from all the found files.<br />
*If you get an error (in ubuntu) concerning libxtst.so install the libxtst-dev package<br />
* If you get the message "kdebase/workspace/kcontrol/kxkb/x11helper.cpp:131: error: ‘KGlobal’ has not been declared", you might need to install libxklavier development packages.<br />
* If you get "/home/kde-devel/kde/lib/libkio.so: undefined reference to `Strigi::AnalysisResult::AnalysisResult(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, long, Strigi::IndexWriter&, Strigi::StreamAnalyzer&)'" you probably have an outdated version of strigi installed by your distro.<br />
<br />
== Running KDE 4 programs ==<br />
<br />
You can now run KDE 4 programs (e.g. kwrite) by typing:<br />
ssh -X kde-devel@localhost<br />
kwrite <br />
<br />
=== Troubleshooting ===<br />
<br />
* If you get <br />
KUniqueApplication: Cannot find the D-Bus session server<br />
check if you can access the display, e.g. type<br />
xclock<br />
and see if a clock appears on the screen.<br />
<br />
* If you get something like<br />
Error: standard icon theme "oxygen" not found!<br />
<br />
ASSERT: "!isEmpty()" in file /home/kde-devel/qt-copy/include/QtCore/../../src/corelib/tools/qlist.h, line 245<br />
Aborted (core dumped)<br />
You need to install kdebase - see above. It is enough to install the "runtime" directory from kdebase.<br />
<br />
== Generating local API documentation ==<br />
Although the API documentation for KDE is available online at [http://api.kde.org api.kde.org], it is sometimes useful to have it on your own disk, for example when you want to use [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|KDevelop]] for browsing the documentation or when you are not able to be online all the time.<br />
<br />
Be aware that generating the API documentation can take several hours and takes almost half a gigabyte of diskspace.<br />
The generation is handled by a script in {{path|kdelibs/doc/api}}, you need <tt>doxygen</tt> to be able to run it. <br />
<br />
To build the API documentation for kdelibs, type the following:<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE/kdelibs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Repeat for other modules as desired.<br><br />
cd <module home><br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Another, even easier method involves downloading this [[Doxyfile]] to your local system. Then simply change directory to where you want to create the documentation and run<br />
<code bash><br />
% doxygen /path/to/Doxyfile<br />
</code><br />
Then review the file {{path|doxygen.log}} to see the doxygen errors and warnings. You'll find the actual documentation in the {{path|apidocs}} subdirectory.<br />
<br />
== Staying up to date ==<br />
<br />
In order to keep the kde4 installation up to date, each of the modules installed should be updated periodically. As Monday is the day for big changes in kdelibs, Tuesday may be the best day to do this. For each module checked out, run <tt>svn up</tt> and <tt>make</tt>.<br />
<br />
For example:<br />
<code bash><br />
cs kdesupport # cs is not a typo<br />
svn up<br />
cb # cb is not a typo<br />
make -j2 VERBOSE=1 && make install<br />
</code><br />
<br />
Note: it is not necessary to run cmakekde for updates.<br />
<br />
== Installing a subset of a module ==<br />
<br />
Many modules in KDE contain a large number of programs which could take a long time to download and compile. In cases where you want to work only on a particular program or programs in a module, it is possible to download and compile particular folders. In some cases, certain folders are required for any build of the module. This is determined in the CMakeLists.txt file of the module. For example the [http://websvn.kde.org/branches/KDE/4.0/kdegames/CMakeLists.txt?view=markup kdegames CMakeLists.txt file] lists:<br />
<br />
<code><br />
add_subdirectory(libkdegames)<br />
add_subdirectory(libkmahjongg)<br />
<br />
macro_optional_add_subdirectory(doc)<br />
macro_optional_add_subdirectory(lskat)<br />
macro_optional_add_subdirectory(katomic)<br />
</code><br />
<br />
So, the libkdegames and libkmahjongg directories are required to build any of kdegames. The cmake directory will also usually be required. All the other directories (doc, katomic etc) are optional. They will be built if present on your machine. In this example, we build kmahjongg and kbattleship:<br />
<br />
<code bash><br />
cs KDE<br />
svn co -N kdegames # The -N switch performs a non-recursive checkout<br />
cd kdegames<br />
svn up libkdegames # Get required directories<br />
svn up libkmahjongg<br />
svn up cmake<br />
svn up kbattleship # Get optional directories<br />
svn up kmahjongg<br />
cmakekde <br />
</code><br />
<br />
== General troubleshooting ==<br />
<br />
What can happen over time, after some <tt>svn up</tt> commands, is that some of the tools used in the KDE build chain change their output format. For example, <tt>kcfg</tt> files are read by <tt>kconfig_compiler</tt> to produce configuration dialogs. CMake cannot detect those changes, and the compilation might fail. A workaround is to always force a re-generation of all such files:<br />
find $KDE_SRC/KDE/kdebase -name "*.kcfg" | xargs touch<br />
The same applies to <tt>ui</tt> files as produced by Qt designer.<br />
<br />
=== Locked sessions ===<br />
When installing KDE 4 as a user, one will not be able to unlock a locked session. To work around this issue you can either:<br />
su chown root.root $KDEDIR/lib/kde4/libexec/kcheckpass<br />
or<br />
chmod 755 $KDEDIR/lib/kde4/libexec/kcheckpass<br />
<br />
Also you have to add a "kde" service in /etc/pam.d/ folder<br />
<br />
For example for RH/Fedora based distros:<br />
<code> <br />
#%PAM-1.0<br />
auth include system-auth<br />
account include system-auth<br />
password include system-auth<br />
session include system-auth<br />
</code><br />
<br />
== Success! ==<br />
<br />
You are now ready to start building other svn modules in the same fashion as you built kdebase, running and testing KDE4 or writing your own patches and applications.<br />
<br />
See the [[Getting Started/Set up KDE 4 for development|Set up KDE 4 for development]] tutorial for how to start KDE 4 applications and how to use KDevelop to work on them.<br />
<br />
[[Category:Build KDE]]<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4&diff=19406Getting Started/Build/KDE42008-01-09T20:40:47Z<p>Powerfox: /* openSUSE */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Getting Started|<br />
<br />
name=Building KDE4 From Source|<br />
<br />
pre=[[../../Sources/Anonymous_SVN|Anonymous SVN Quickstart Guide]]|<br />
<br />
next=[[../../Set_up_KDE_4_for_development|Set up KDE 4 for development]]|<br />
<br />
reading=[[../kdesvn-build|kdesvn-build: The KDE From Subversion Build Tool]]<br>[[../../Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br>[[Development/Tutorials/CMake |Introduction to CMake]]<br>[[../KDE4/FreeBSD|FreeBSD notes]]<br>[[../KDE4/Mac OS X|Instructions for Mac OS X]]<br>[[../KDE4/Windows|Instructions for MS Windows]]|<br />
}}<br />
<br />
== Abstract ==<br />
<br />
This tutorial shows one way to get KDE from trunk running on Linux/BSD systems. There are also tutorials for [[Getting_Started/Build/KDE4/FreeBSD|FreeBSD]], [http://www.kdelibs.com/ Windows], [[Getting_Started/Build/KDE4/Mac OS X|Mac OS X]] and [http://solaris.kde.org/ Solaris]. Throughout the tutorial the bash shell is used.<br />
<br />
{{warning|Expect a higher risk of build failure '''on Mondays''' when most kdelibs changes are committed. [http://developer.kde.org/~dirk/dashboard/ Dashboard] reports unexpected breakages. You are encouraged to fix failing modules.<br />
}}<br />
<br />
== Software Requirements ==<br />
<br />
The following needs to be installed to successfully use this tutorial:<br />
* gcc and g++, preferably version 4.2 or higher<br />
* svn, the subversion revision control client<br />
* pkg-config<br />
* development libraries and headers for X11, OpenGL (mesa-common-dev and libglu1-mesa-dev), libjpeg, libpng, libungif, [http://clucene.sourceforge.net/index.php/Downloads libclucene], [http://download.librdf.org/source/ librdf], libxml2 and libxslt<br />
* the <tt>makeobj</tt> script, which is included in kdesdk. You can install it from kdesdk (kdesdk-scripts on Debian) or similar packages, or download at [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/makeobj WebSVN]<br />
* the [http://freedesktop.org/wiki/Software/shared-mime-info shared-mime-info package], is the freedesktop MIME standard now used in KDE<br />
* [http://boost.org/ boost], used by kdebase; after build and/or install, in order to make cmake aware about its location (FindBoost), add the boost directory (which contains the include subdirectory) to CMAKE_INCLUDE_PATH or set a environment variable called BOOST_ROOT that points to the boost directory.<br />
<br />
=== Ark Linux ===<br />
In Ark Linux, the build dependencies you need are installed with:<br />
<br />
<code bash><br />
apt-get install devel-core libxml-devel libxslt-devel bzip2-devel \<br />
clucene-core-devel librdf-devel shared-mime-info xorg-Mesa-libGL-devel \<br />
subversion boost-devel doxygen giflib-devel dbus-devel openssl-devel \<br />
alsa-lib-devel kdesdk-scripts qt4-devel<br />
</code><br />
<br />
If you prefer a graphical interface, select the packages listed above in the "Install Software" tool in Mission Control.<br />
<br />
This includes installation of CMake, DBus and Qt - you can skip steps 5, 6 and 7.<br />
<br />
=== Arch Linux ===<br />
In Arch Linux you need to install the following packages:<br />
<br />
<code bash><br />
pacman -Sy subversion bzip2 libxslt libxml2 \<br />
shared-mime-info mesa boost dbus openssl \<br />
pkgconfig xine-lib clucene<br />
</code><br />
<br />
If you want to use qt4 from the Arch Linux repository you can install it with:<br />
<code bash><br />
pacman -Sy qt4<br />
</code><br />
("pacman -Sy qt" if you are running bleeding-edge Arch Testing)<br />
<br />
<s>For clucene libraries you need the [http://aur.archlinux.org/packages.php?do_Details=1&ID=5968 PKGBUILD] from AUR.</s><br />
(No longer needed since clucene has been put into the extra-repo.)<br />
<br />
=== Fedora ===<br />
<br />
Some of the required packages for building KDE4 on Fedora 7 or higher:<br />
<br />
<code bash><br />
yum install clucene-core-devel libxml-devel libxslt-devel \<br />
dbus-devel boost-devel bzip2-devel openssl-devel alsa-lib-devel \<br />
redland-devel rasqal-devel raptor-devel hspell-devel aspell-devel \<br />
cups-devel xine-lib-devel avahi-devel gamin-devel OpenEXR-devel \<br />
enchant-devel jasper-devel ilmbase-devel pcre-devel gpgme-devel \<br />
libxklavier-devel glib-devel libusb-devel libsmbclient-devel \<br />
libxcb-devel NetworkManager-devel lm_sensors-devel libraw1394-devel \<br />
bluez-libs-devel gcc-c++ libXext-devel cmake subversion giflib-devel \<br />
libpng-devel libXdamage-devel libXcomposite-devel libXrender-devel \<br />
fontconfig-devel libXft-devel libXcursor-devel libXfixes-devel \<br />
ruby-devel libXScrnSaver-devel libkdcraw-devel exiv2-devel \<br />
lcms-devel libtiff-devel sqlite-devel libxkbfile-devel \<br />
imlib2-devel patch gstreamer-plugins-base-devel gsl-devel<br />
</code><br />
<br />
Some optional packages for koffice support:<br />
<code bash><br />
yum install qca2-devel gsl-devel freeglut-devel \<br />
GraphicsMagick-c++-devel GraphicsMagick-devel<br />
</code><br />
<br />
This includes installation of D-Bus and CMake -- you can skip steps 5 and 6.<br />
<br />
DCH-10/15/07: Note - It may be simpler to spin RPMs. Note that you can edit the variables in /etc/rpm/macros.kde4 (which is provided by Rawhide kde-filesystem).<br />
<br />
The build stage then looks like:<br />
(but in what directory?)<br />
%build<br />
<br />
mkdir -p %{_target_platform}<br />
<br />
pushd %{_target_platform}<br />
<br />
%{cmake_kde4} ..<br />
<br />
popd<br />
<br />
make %{?_smp_mflags} -C %{_target_platform}<br />
<br />
I have had better results with creating a kdesupport rpm which means that you should not install the soprano and strigi rpms. YMMV<br />
<br />
telsh: On a Fedora 8 System I had to install "qt4-devel" too to have qmake.<br />
<br />
=== Kubuntu and Debian ===<br />
<br />
In Kubuntu 7.04 (Feisty) and Debian (Testing/Unstable) the build dependencies you need are installed with:<br />
<code><br />
sudo aptitude install build-essential cdbs debhelper cmake \<br />
libxml2-dev libxslt1-dev libbz2-dev libclucene-dev librdf-dev \<br />
shared-mime-info libgl1-mesa-dev libglu1-mesa-dev mesa-common-dev \<br />
libxext-dev libjpeg-dev libpng12-dev subversion libsm-dev libxinerama-dev \<br />
libxrender-dev libfontconfig-dev libboost-dev libxcursor-dev doxygen \<br />
libungif4-dev libdbus-1-dev libssl-dev libgpgme11-dev \<br />
libasound2-dev kdesdk-scripts libpth-dev libjasper-dev \<br />
ssh libxine-dev libqimageblitz-dev libqimageblitz4 libglib2.0-dev \<br />
libxkbfile-dev libenchant-dev libbluetooth-dev network-manager-dev \<br />
libsmbclient-dev libxcb1-dev libcaptury-dev libxcomposite-dev \<br />
libxdamage-dev libusb-dev libgpgme11-dev libldap2-dev<br />
</code><br />
<br />
In Kubuntu 7.10 (Gutsy) and Debian unstable you also have to add:<br />
<code><br />
sudo aptitude install dbus-x11 libqt4-dev libqca2-dev libeigen-dev \<br />
libstreamanalyzer-dev libsoprano-dev libstrigiqtdbusclient-dev \<br />
libxklavier11-dev libxml2-utils libdbus-1-dev libxslt1-dev cmake libbz2-dev \<br />
libungif4-dev libgpgme11-dev libboost-dev libxine-dev libxkbfile-dev<br />
</code><br />
<br />
For a fully functional API documentation framework you also need:<br />
<code><br />
sudo aptitude install graphviz<br />
</code><br />
<br />
There is no need to compile qt or kdesupport on kubuntu gutsy. All required packages are provided by installing the above. Setup the kde4 user etc as explained in the next section, but skip over compiling qt, hal and kdesupport.<br />
<br />
{{Note|<br />
If you get something trouble on compile KDE4<br />
Beta4 or above in Kubuntu 7.10, such as :<br />
<br />
Soprano version is too low<br />
<br />
strigi xxx.h not found...<br />
<br />
You may need to checkout, and compile the relevant part of<br />
kdesupport source code in the SVN server of KDE4. (svn://anonsvn.kde.org/home/kde/trunk/kdesupport/soprano/) <br />
<br />
This is covered when you get to the section on compiling kdesupport.<br />
<br />
You might also have to remove any installed soprano package : sudo apt-get remove libsoprano4 libsoprano-dev<br />
<br />
If you still get an error in the kdelibs section about soprano like:<br />
CMake Error: Error in cmake code at<br />
$src/KDE/kdelibs/cmake/modules/FindSoprano.cmake:78:<br />
FILE Internal CMake error when trying to open file: /usr/include/soprano/version.h for reading.<br />
<br />
then delete kdelibs/CMakeCache.txt<br />
}}<br />
<br />
=== openSUSE ===<br />
<br />
In openSUSE 10.2 and newer, you can install packages using [http://en.opensuse.org/Zypper Zypper]:<br />
<code bash><br />
sudo zypper install <package-name><br />
</code><br />
<br />
In older releases of SUSE, you can use YaST:<br />
<code bash><br />
su<br />
yast -i <packagename><br />
</code><br />
<br />
'''Required Packages'''<br />
<br />
The packages you will need to install are:<br />
<code><br />
xorg-x11-devel<br />
libxml2-devel <br />
kdesdk3 <br />
clucene-core-devel <br />
boost-devel<br />
libjpeg-devel <br />
liblrdf-devel <br />
libpng-devel <br />
libxslt-devel <br />
libredland-devel<br />
Mesa-devel <br />
giflib-devel <br />
subversion <br />
gcc <br />
gcc-c++<br />
gmp-devel (needed to build kdesupport)<br />
xine-devel<br />
libgpgme-devel (needed to build kdepimlibs)<br />
</code><br />
<br />
'''Optional Packages'''<br />
<br />
You can skip the manual and painful installation kdesupport and its dependencies ( Qt 4.3, CMake 2.4.6, DBus, Hal, clucene-core, Strigi,<br />
Soprano and other Nepomuk dependencies) by adding the KDE:KDE4 repository from<br />
the [http://download.opensuse.org/repositories/KDE:/KDE4/ openSUSE Build Service] to your installation sources. <br />
<br />
For openSUSE 10.2 and newer do:<br />
<code><br />
sudo zypper service-add http://software.opensuse.org/download/KDE:/KDE4/openSUSE_10.2 KDE4-102<br />
</code><br />
<br />
For older versions of SUSE Linux do:<br />
<code><br />
su<br />
installation_sources -a http://software.opensuse.org/download/KDE:/KDE4/[YOUR SUSE LINUX VERSION]<br />
</code><br />
<br />
Now install the following packages:<br />
<code><br />
cmake<br />
dbus-1-devel<br />
libqt4-devel<br />
libqca2-devel<br />
libsoprano-devel<br />
libqimageblitz-devel<br />
strigi<br />
strigi-ui<br />
</code><br />
<br />
There are a lot more packages that are needed to satisfy the config-check, such as libusb-devel, bison etc., so look out for the config notifications and install accordingly. Please remember to skip any instructions that refer to kdesupport below. Start to compile with kdelibs. <br />
<br />
And for fully functional apidox framework you also need:<br />
<code><br />
graphviz<br />
</code><br />
<br />
CMake binary packages for openSUSE are available from the KDE:KDE4 repository as well as from the [http://software.opensuse.org/download/devel:/tools:/building/ openSUSE build service].<br />
<br />
=== Gentoo ===<br />
<br />
==== Install by hand ====<br />
<br />
You can use stable ebuilds just remember to sync your portage before you begin.<br />
<br />
Remember: All commands are executed as root.<br />
<br />
Required:<br />
<br />
We need to allow the following keyword masked ebuilds.<br />
<br />
<code bash><br />
echo 'dev-util/cmake' >> /etc/portage/package.keywords<br />
echo 'dev-cpp/clucene' >> /etc/portage/package.keywords<br />
</code><br />
<br />
Make sure you have set the berkdb USE flag for redland, otherwise nepomuk won't work.<br />
<br />
<code bash><br />
echo 'dev-libs/redland berkdb' >> /etc/portage/package.use<br />
echo 'x11-libs/qt accessibility' >> /etc/portage/package.use<br />
</code><br />
<br />
These are the packages you will need to emerge, I included the update option into the emerge command so you will not re-emerge anything that you might already have installed.<br />
<br />
<code bash><br />
emerge -avu 'sys-devel/gcc' \<br />
'dev-util/subversion' \<br />
'dev-util/pkgconfig' \<br />
'x11-base/xorg-x11' \<br />
'virtual/glut' \<br />
'media-libs/mesa' \<br />
'media-libs/jpeg' \<br />
'media-libs/libpng' \<br />
'media-libs/giflib' \<br />
'dev-cpp/clucene' \<br />
'dev-util/cppunit' \<br />
'media-libs/liblrdf' \<br />
'dev-libs/libxml2' \<br />
'dev-libs/libxslt' \<br />
'x11-misc/shared-mime-info' \<br />
'dev-libs/boost' \<br />
'dev-util/cmake' \<br />
'dev-libs/redland' \<br />
'sys-apps/dbus' \<br />
'sys-apps/hal' \<br />
'x11-libs/qt'<br />
</code><br />
<br />
You will also need to emerge either 'kde-base/kdesdk' or kde-base/kdesdk-scripts'.<br />
<br />
If you emerged DBUS, CMAKE, QT or HAL you may skip those sections respectively.<br />
Good luck!<br />
<br />
==== Install via portage ====<br />
<br />
Also you can install the KDE 4 packages directly via <br />
<code bash><br />
emerge -a <packagename><br />
</code><br />
<br />
To get the things you need, [http://gentoo-wiki.com/TIP_Overlays#Layman install layman] and then pull in the "kde" overlay (which contains experimental KDE ebuilds): <br />
<code bash><br />
layman -a kde<br />
</code><br />
After this you need to adjust some USE-flags for KDE 4 and tell portage to use the testing KDE 4 ebuilds instead of the stable KDE 3 ones. <br />
<br />
That way portage will do the dependency tracking for you. <br />
<br />
Detailed instructions on building KDE 4 in Gentoo via portage can be found in the [http://overlays.gentoo.org/proj/kde/wiki KDE overlay wiki]. They are discussed in the forum thread [http://forums.gentoo.org/viewtopic-t-530111-postdays-0-postorder-asc-start-0.html KDE 4 monolithic ebuilds], which is continued [http://forums.gentoo.org/viewtopic-p-4359581.html#4359581 here]<br />
<br />
=== Mandriva ===<br />
In Mandriva the build dependencies you need are installed with:<br />
<br />
<code bash><br />
urpmi gcc-c++ cmake libxml2-devel libbzip2_1-devel \<br />
libclucene0-devel liblrdf2-devel libmesagl1-devel \<br />
subversion doxygen libdbus-1_3-devel libopenssl0.9.8-devel \<br />
libalsa2-devel libgpgme-devel libboost1-devel libxine-devel<br />
</code><br />
<br />
If you're running 64-bit environment you should replace all packages starting with "lib..." to "lib64...".<br />
<br />
If you prefer a graphical interface, select the packages listed above in the "Install Software" tool in Mandriva Linux Control Center.<br />
<br />
This includes installation of CMake, DBus - you can skip steps 5 and 6.<br />
<br />
== Create a user account for KDE4 development ==<br />
<br />
{{Note|<br />
Some people like to have a separate user account for KDE 4 (for instance an old bug deleted files by mistake), and the instructions below were written with that approach.<br />
<br />
However it is much more efficient to do everything with a single user account, see [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br />
for more details. <br />
<br />
You can still follow the instructions below, but don't put the environment variables in your <tt>.bashrc</tt>, put them in a separate file that you source to switch to the KDE 4 environment.<br />
}}<br />
<br />
=== Option 1: Command Line ===<br />
<code bash><br />
useradd -m kde-devel<br />
passwd kde-devel<br />
</code><br />
<br />
<br />
{{Warning|<br />
The new kde-devel user will not be added automatically to all the user groups, which will result in not having sound, not being able to sudo, etc. Edit your /etc/groups file to add the kde-devel user to all the groups that you need (probably the groups that your usual username is already assigned to).<br />
}}<br />
<br />
=== Option 2: Using KControl ===<br />
<br />
Instead of using the commands above, you can also use the User module in the KDE Control Center if you already have KDE3 installed.<br />
<br />
=== Setting up the environment ===<br />
<br />
Copy the {{path|~/.bashrc}} from your normal user account to the new kde-devel account. Next, copy and paste the contents of the [[Getting Started/Increased Productivity in KDE4 with Scripts/.bashrc|example .bashrc]] into {{path|~kde-devel/.bashrc}}. Be sure to comment out the line <tt>alias make=makeobj</tt> if you do not have the <tt>[[Getting Started/Build/KDE4#Required Software|makeobj]]</tt> command available. You will probably also want to modify the path to make sure it doesn't include your kde3 paths. Also if you want to use KDevelop to develop KDE 4 applications you may pass the ''-GKDevelop3'' flag to the ''cmake'' command (to make CMake generate KDevelop project files, it will help to avoid rebuilding in the future, see [[Getting_Started/Set_up_KDE_4_for_development#Setting_up_the_environment|this]]). <br />
To make it run, you have to open a new bash or to execute <br />
<code bash><br />
source ~/.bashrc<br />
</code><br />
<br />
This will provide access to commands such as <tt>cmakekde</tt> that are used in this tutorial as well as ensure that the proper paths are in place for Qt, KDE and CMake binaries.<br />
<br />
For more information, please read the [[Getting Started/Increased Productivity in KDE4 with Scripts]] tutorial.<br />
<br />
=== Switching to the New User ===<br />
Switch to the user kde-devel: (don't forget the dash)<br />
<code bash><br />
ssh -X kde-devel@localhost<br />
</code><br />
<br />
{{Note|<br />
If the ssh command fails, check out the [[Getting_Started/Set_up_KDE_4_for_development#Launching_KDE_4_apps|Launching KDE 4 apps]] section of the [[Getting_Started/Set_up_KDE_4_for_development|KDE4 development guide]].<br />
}}<br />
<br />
== The development user's shell ==<br />
<br />
On some systems a new user is configured by default to use {{path|/bin/sh}}. If this is not the case on your system, you can skip this section. Using {{path|/bin/sh}} can be very inconvenient to work with and you may want to change it to {{path|/bin/bash}} or another shell.<br />
On Ark Linux and Fedora, you can skip this step - {{path|/bin/sh}} is {{path|bash}}.<br />
<br />
=== Option 1: As the kde-devel user ===<br />
<br />
If you don't have root privileges and your system supports the changing of your own shell with the <tt>chsh</tt> application, then you could try to change your shell to {{path|/bin/bash}} by using:<br />
<code bash><br />
chsh -s /bin/bash kde-devel<br />
</code><br />
<br />
=== Option 2: As the root user ===<br />
<br />
If your system comes with the <tt>usermod</tt> application you can run the following command as root: <tt>usermod -s /bin/bash kde-devel</tt>.<br />
<br />
Another option is to use the <tt>vipw</tt> application as root to safely edit your {{path|/etc/passwd}}. Locate 'kde-devel' in the the file. Change '{{path|/bin/sh}}' at the end of the line to read '{{path|/bin/bash}}', save your changes and exit.<br />
<br />
The new shell will be started automatically when you log in as the kde-devel user again.<br />
<br />
== D-Bus ==<br />
QtDBus and KDE are known to work with D-Bus versions 0.62, as well as 0.92 and upwards. Versions 0.60 and 0.61 may work too but are not tested. Versions 0.90 and 0.91 are known not to work. We recommend using post-1.0 release versions (at least 0.94), so consider upgrading if you haven't done so.<br />
<br />
You may skip this section if you have a recent D-Bus version or if you don't want to upgrade. You probably want to skip building the bindings until/unless you know you will be building HAL (see below).<br />
<br />
Before running these steps in the recipe, make sure your X11 headers and libraries are available. The configure script run on line 5 of the following instructions should output:<br />
Building X11 code: yes<br />
<br />
=== The Recipe ===<br />
<br />
{{tip|Make sure you did set up your environment correctly as described [[Getting_Started/Build/KDE4#Setting_up_the_environment|above]]. This is necessary for the <tt>cs</tt> and <tt>cb</tt> functions to work.}}<br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]] <br />
wget http://dbus.freedesktop.org/releases/dbus/dbus-1.0.2.tar.gz<br />
tar -xvzf dbus-1.0.2.tar.gz<br />
cd dbus-1.0.2/<br />
./configure --prefix=$DBUSDIR --localstatedir=/var<br />
make<br />
sudo make install<br />
sudo dbus-uuidgen --ensure<br />
<br />
cs # see above<br />
wget http://dbus.freedesktop.org/releases/dbus-glib/dbus-glib-0.74.tar.gz<br />
tar -xvzf dbus-glib-0.74.tar.gz<br />
cd dbus-glib-0.74/<br />
./configure --prefix=$DBUSDIR<br />
make<br />
sudo make install<br />
cd<br />
sudo chown -R kde-devel:kde-devel *<br />
<br />
=== What's Happening === <br />
After changing into the source directory (line 1), D-Bus source code is downloaded from freedesktop.org (line 2) and unpacked (line 3). After going into the newly created D-Bus directory (line 4), the build is set up using the supplied {{path|configure}} script (line 5). After building (line 6) and installing (line 7) D-Bus, we use the <tt>dbus-uuidgen</tt> tool to install a machine identification file that allows the bus to start automatically when the desktop session starts (line 8).<br />
<br />
Note that you need write access to {{path|/var}} for the last two steps. If your system does not have the sudo command, you can use the <tt>su</tt> command instead, e.g. <tt>su -c "make install"</tt>.<br />
<br />
The steps for building the glib bindings are similar to the above.<br />
<br />
When these two packages are done building, we must fix the file ownership because 'sudo make install' has created root owned files and directories in ~kde-devel/kde.<br />
<br />
== CMake ==<br />
Skip this if you have [http://cmake.org/ CMake] >=2.4.5 installed. <br />
You should be able to directly use the binary packages available on the [http://www.cmake.org/HTML/Download.html CMake site]. There are also distribution specific packages available.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click Here to learn more]] <br />
wget http://www.cmake.org/files/v2.4/cmake-2.4.6.tar.gz<br />
tar -zxf cmake-2.4.6.tar.gz<br />
mkdir cmake-build<br />
cd cmake-build <br />
../cmake-2.4.6/bootstrap<br />
make<br />
sudo make install<br />
<br />
=== What's Happening ===<br />
First, we go back to the <tt>kde-devel</tt> user's source directory (line 1), get the CMake sources (line 2) and unpack them (line 3). We create a directory to build CMake in (line 4) and go into it (line 5). We then run the CMake bootstrap script to set up the CMake build (line 6), then make (line 7) and install it (line 8) using the root user.<br />
<br />
If your system does not have the <tt>sudo</tt> command, you can instead do <tt>su -c "make install"</tt>.<br />
<br />
== Qt ==<br />
Next we need to get Qt4. KDE is guaranteed to build against any Qt 4.3. Qt 4.2 and earlier are not supported and will not work. <br />
<br />
If your distribution has a recent version of Qt4, that should work. Most distros backport bugfixes, and some distros, like Debian or openSUSE, even use the patches from KDE svn. In other cases, using the recipe below will give you a more stable Qt than your distro. Refer to the distribution specific sections above for more information. <br />
<br />
As for now Qt3 compatibility layer in Qt 4 is mandatory, so please <b>avoid</b> using "-no-qt3support" option when building Qt4 from sources.<br />
<br />
=== The Recipe ===<br />
cd # Note: qt-copy lives in $HOME/qt-copy. See $QTDIR in [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|<font color=red>.bashrc</font>]] <br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/qt-copy<br />
cd qt-copy<br />
./apply_patches<br />
./configure -qt-gif -no-exceptions -debug -fast \<br />
-prefix $QTDIR -nomake examples -nomake demos<br />
make -j2<br />
<br />
# if we don't install, we'll just clear obj files to<br />
# save disk space<br />
if [ $QTDIR = `pwd` ]; then \<br />
find . -name '*.o' -delete ; \<br />
else make install; fi;<br />
<br />
=== What's Happening ===<br />
We switch back to the <tt>kde-devel</tt> user's home directory (line 1) and download the source code using subversion (svn) from KDE's repository (line 2). After changing into the resulting {{path|qt-copy}} directory (line 3), we run a script that manages the patches that come with <tt>qt-copy</tt> (line 4). <br />
<br />
Once the patches have been applied, we then set up the build using the <tt>configure</tt> script (line 5-6). The various command line options used are explained in the {{path|qt-copy/README.qt-copy}} file. Finally, we build the minimal requirements for KDE (line 7) and install (line 10) Qt. If install dir is the same as the current dir (line 8), then we just free some space (line 9) instead. If you want all the example and demo applications, you can either build them individually or simply do a <tt>make</tt> from the {{path|qt-copy}} directory. <br />
<br />
Note that the installation does not require root as it installs Qt locally into {{path|$QTDIR}}. Anyway, installation is only needed if {{path|$QTDIR}} differs from {{path|$HOME/qt-copy}}, which is not the case if you have exactly followed the instructions.<br />
<br />
=== Troubleshooting ===<br />
If you get "error: X11/Xlib.h: No such file or directory", install the devel package of <tt>xorg</tt> (the actual name may vary between operating systems, for example it is <tt>xorg-dev</tt> on Ubuntu based systems such as Kubuntu). <br />
<br />
If you get an error in the configure step about missing defines, check the value of <tt>$QMAKESPEC</tt>. Some distributions set this to point directly to the system-installed Qt. If <tt>unset QMAKESPEC</tt> solves the problem, you probably want to add it to the <tt>~/.bashrc</tt> script.<br />
<br />
If you get an error ".pch/debug-shared/QtCore", this is because Qt-4.3 enables precompiled headers if your gcc supports it, but for some reason it doesn't work for you. If you use distcc, configure qt with -no-pch. If you use icecream, update to the latest icecream from svn trunk.<br />
<br />
Try running any Qt program, like {{program|assistant}}. '''Note:''' You may need to run <tt>xhost +local:kde-devel</tt> as your regular kde3 user to run this application. If it crashes in QSpanData::adjustSpanMethods, then your problem is the oxygen style. Try removing {{path|lib/kde4/plugins/styles/kstyle-oxygen.so}} and {{path|lib/kde4/plugins/styles/oxygen.so}} if they exist in the KDE install prefix.<br />
<br />
== HAL ==<br />
<br />
{{tip|You can use qdbusviewer to see if you have org.freedesktop.hal. If not, you might need a newer version of hal. If you have org.freedesktop.hal, you probably don't need to, and don't ''want'' to, roll your own HAL.}}<br />
<br />
If your system requires you to build a newer version of HAL, there's a decent chance you'll need to build other stuff as well, some of which may not be straight forward. Since this should only be required for older distros, instructions are on [[Getting_Started/Build/HAL| a separate page]].<br />
<br />
== kdesupport ==<br />
<br />
{{warning|Don't forget to read the [[Getting_Started/Build/KDE4#Setting_up_the_environment|Setting Up The Environment]] section first.}}<br />
<br />
There are several libraries that KDE applications rely on in the kdesupport module. This includes Strigi and Soprano for file metadata and search, QImageBlitz for image manipulation needed in kdebase, eigen for visual effects in applications such as Kalzium, taglib for music players and qca for some cryptographic needs. <br />
<br />
Strigi itself has a few dependencies as well: you will need the libraries and headers for libz, libbz2, openssl (libcrypto or libssl), libclucene (>=0.9.16a but watch out: version 0.9.17 does '''not''' work), and either libxml2 or libexpat.<br />
<br />
Please remember that if you use openSUSE, you can install the needed packages from the KDE:KDE4 buildservice repository and do not have to bother with fiddling the details below. Skip to the kdelibs section. <br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/kdesupport/<br />
cd kdesupport<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1). We download the sources in kdesupport using subversion (line 2), go into the new {{path|~/kde/src/kdesupport}} directory (line 3), and commence the build (line 4). This will leave us in the kdesupport build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you get <br />
cmakekde: command not found<br />
then you have to go manually into the kdesupport directory in ~ and execute the command cmakekde. if this still doesn't work, then something is wrong with your bashrc.<br />
<br />
If you get <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 />
LIBXML2_INCLUDE_DIR (ADVANCED)<br />
you should install the development package for libxml2.<br />
<br />
If you get <br />
CMake Error: Could NOT find REDLAND<br />
then you need librdf from the Redland.<br />
If your distribution does not provide the librdf package, you can download the source there: [http://download.librdf.org/source/ http://download.librdf.org/source/] and build it.<br />
(Gentoo users: The ebuild for librdf is named dev-libs/redland)<br />
<br />
If you get<br />
Fetching external item into 'kdesupport/admin'<br />
Error validating server certificate for 'https://...'<br />
see [http://techbase.kde.org/Getting_Started/Sources/Using_Subversion_with_KDE Using Subversion with KDE]<br />
<br />
If you get<br />
FILE cannot create directory: /usr/lib[64]/qt4/plugins/crypto. Maybe need administrative privileges.<br />
<br />
make: *** [install] Error 255<br />
take a second look in the .bashrc file described above, are paths correct? ($QTDIR and $PATH are used to get the QT installation path)<br />
Alternatively, you may see this error if you decided to use a distribution installed version of qt4 and skipped the Qt install above. Either install qt-copy as describe above, or "sudo make install". If you use "sudo make install", make sure that you change the ownership back to your user for some of the ~/kde subdirectories that were effected by using sudo (ie. "<tt>sudo chown -R kde-devel:kde-devel ~/kde</tt>").<br />
<br />
If you get a message related to <br />
target libQtTest.so not found<br />
you may need to recompile qt-copy. This time you should take out<br />
-nomake demos -nomake examples<br />
from the configure command, so that Qt generates library QtTest.<br />
<br />
== kdelibs ==<br />
<br />
We can now move on to building KDE's base libraries.<br />
<br />
=== The Recipe ===<br />
cd <br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
mkdir KDE && cd KDE<br />
svn checkout svn://anonsvn.kde.org/home/kde/branches/KDE/4.0/kdelibs<br />
cd kdelibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1) then make and go into the KDE directory (line 2). We download the sources for kdelibs using subversion (line 3), go into the new {{path|~/kde/src/KDE/kdelibs}} directory (line 4), and commence the build (line 5). This will leave us in the <tt>kdelibs</tt> build directory after the build is completed.<br />
<br />
{{tip|There might be missing dependencies on your system! They are easily overlooked in the output of <tt>cmakekde</tt>.<br />
You might want to do a <tt>cmake $KDE_SRC/KDE/MODULE_NAME</tt> prior to compiling any kde modules (like kdelibs, kdepimlibs etc.)}}<br />
<br />
=== Additional KDE-specific CMake modules ===<br />
There are additional CMake modules in {{path|kdelibs/cmake/modules/}} that are necessary for building KDE4 applications. These will be installed for you when kdelibs itself is installed.<br />
<br />
=== Troubleshooting ===<br />
If you have problems compiling kdelibs, first make sure the software in the [[Getting_Started/Build/KDE4#Software_Requirements|Required Software]] section above is installed and works. Other possible hints include:<br />
* If the <tt>cmakekde</tt> command fails stating that CMake requires an out of source build directory, remove {{path|~/kde/src/KDE/kdelibs/CMakeCache.txt}}, and try again.<br />
<br />
If <tt>cmakekde</tt> still gives the same error then try this <br />
cd<br />
cmake -DCMAKE_INSTALL_PREFIX=$KDEDIR \<br />
-DCMAKE_BUILD_TYPE=debugfull \<br />
-DKDE4_BUILD_TESTS=ON \<br />
~/kde/src/KDE/kdelibs<br />
make<br />
make install<br />
* If you received an error stating "Please create a separate build directory and run 'cmake path_to_kdelibs [options]' there.", then you need to change to your build directory before running cmakekde. (e.g <tt>cs KDE/kdelibs && cb && cmakekde</tt>) If the message stays, run 'svn status' in the kdelibs directory and remove all files labeled with '?'.<br />
* If Qt wasn't found or the wrong version of Qt was found, make sure that the qmake from the Qt you need is the first qmake in the path.<br />
* If qmake wasn't found and you are using Debian packages, /usr/bin/qmake probably points to a wrong qmake version. To fix this run as root:<br />
update-alternatives --config qmake<br />
* If the problems persist, try the CMake make-option <tt>--keep-going</tt>.<br />
* Here you need the libungif library, otherwise you will get an error message like "<tt>Could NOT find GIF</tt>".<br />
* Qt-4.3 upgrade: if you get a link error in kjsembed talking about QScriptEngine, edit CMakeCache.txt in kdelibs and remove the lines that talk about QT_QTUITOOLS_LIBRARY, then type make again (that static library has a new dependency, and the cmake code that adds it needs to run).<br />
* if you get <code>CMake Error: KDE Requires Qt to be built with SSL support<br />
</code>, install openssl-devel, remove CMakeCache.txt and re-compile QT.<br />
* if you get <code>kdelibs/kimgio/ico.cpp:188: undefined reference to `QImage::jumpTable()'</code> it means you compiled QT without QT3 support(no, linking to a true QT3 install won't work)<br />
* if none of the errors above match yours, you might just try a quick'n'dirty <code>make clean</code> in kdelibs.<br />
<br />
== kdepimlibs ==<br />
After <tt>kdelibs</tt>, but before ''kdebase'', you need to build and install ''kdepimlibs''.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/branches/KDE/4.0/kdepimlibs<br />
cd kdepimlibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We go into the KDE source directory (line 1), download the source code for kdepimlibs using subversion (line 2) and then go into the new {{path|~/kde/src/KDE/kdepimlibs}} directory (line 3). We then commence the build (line 4). This will leave us in the <tt>kdepimlibs</tt> build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you have trouble compiling kdepimlibs:<br />
* the cmakekde command may require a later version of the gpgme library. This is available from the project's web site: http://www.gnupg.org/(en)/download/index.html - please note that the build of gpgme also requires libgpg-error, also available from the same location. Both libraries are installed by the "./configure", "make" and "sudo make install" sequence, with the gpgme library configured with the additional "--with-gpg-error-prefix" parameter. You may need to overwrite your existing "/usr/bin/gpgme-config" file with the newer version for the kdepimlibs to pick up the new install.<br />
<br />
== kdebase ==<br />
kdebase is divided into three parts:<br />
* '''apps'''<br />
:This contains applications like Dolphin or KWrite.<br />
* '''runtime'''<br />
:This contains things needed by every application at runtime, like icons. It is a required dependency for each KDE application, so you have to compile and install this.<br />
* '''workspace'''<br />
:This contains things specific to the KDE desktop, like Plasma or the window manager. Most stuff here depends on X11. You only need it if you want to build a full KDE desktop.<br />
<br />
You can build all of kdebase at once, which is described in the recipe below. If you only want to build kdebase-runtime, which is the only requirement, you can replace <code bash>cd kdebase</code> with <code bash>cd kdebase/runtime</code> in the recipe below.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/branches/KDE/4.0/kdebase<br />
cd kdebase<br />
cmakekde<br />
<br />
=== Troubleshooting ===<br />
If you have troubles compiling kdebase:<br />
* Make sure you have the <tt>libxss headers</tt> installed. (Usually you got undefined references on xscreensaver objects if you do not have those headers)<br />
* <tt>which meinproc</tt> has to deliver {{path|/home/kde-devel/kde/bin/meinproc}}<br />
* if cmakekde can not find the path of kdepimlibs, edit the file {{path|$KDE_BUILD/KDE/kdebase/CMakeCache.txt}} and manually set <tt>KDEPIMLIBS_INCLUDE_DIR:PATH=$KDE_BUILD/kdepimlibs</tt><br />
* if you get an error saying "Please set the following variables: X11_XTest_LIB (ADVANCED)", install the devel package of <tt>Xtst</tt>. On some systems, this is packaged separately from <tt>xext</tt> and called <tt>x11proto-xext-dev</tt> or <tt>libxtst-dev</tt>. You may also need to remove the CMakeCache.txt file in the build dir after installing the package.<br />
* the same for "X11_Xinerama_LIB (ADVANCED)" where you will need the devel package for <tt>xinerama</tt>.<br />
* if you get an error complaining about a missing variable X11_Xrandr_LIB, you need the devel package for libxrandr (libxrandr-devel on ubuntu-systems)<br />
* if you get the error "Please set the following variables: FONTCONFIG_INCLUDE_DIR, FONTCONFIG_LIBRARIES (ADVANCED)", then you need to install the libfontconfig headers<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: KMETADATA_LIBRARIES", you need to install soprano from kdesupport and to rebuild kdelibs<br />
* if you get the error "‘XserverRegion’ does not name a type" make sure you have libxcomposite headers installed (<tt>libxcomposite-dev</tt> in ubuntu)<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: QT_QTOPENGL_LIBRARY (ADVANCED) ", try editing CMakeCache.txt and setting QT_QTOPENGL_LIBRARY:FILEPATH=/home/kde-devel/qt-copy/lib/libQtOpenGL.so<br />
<br />
* if you get messages as "KDE4_INSTALL_HANDBOOK() is deprecated. Remove it please. Now all is done in KDE4_CREATE_HANDBOOK." then, either find the files containing the offending line and comment it out manually, or run the following script in ~/kde/src/KDE/kdebase: [http://www.plamadeala.com/files/macros_corrector.sh macros_corrector.sh]. It will just REMOVE the line that has "kde4_create_handbook" in it from all the found files.<br />
*If you get an error (in ubuntu) concerning libxtst.so install the libxtst-dev package<br />
* If you get the message "kdebase/workspace/kcontrol/kxkb/x11helper.cpp:131: error: ‘KGlobal’ has not been declared", you might need to install libxklavier development packages.<br />
* If you get "/home/kde-devel/kde/lib/libkio.so: undefined reference to `Strigi::AnalysisResult::AnalysisResult(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, long, Strigi::IndexWriter&, Strigi::StreamAnalyzer&)'" you probably have an outdated version of strigi installed by your distro.<br />
<br />
== Running KDE 4 programs ==<br />
<br />
You can now run KDE 4 programs (e.g. kwrite) by typing:<br />
ssh -X kde-devel@localhost<br />
kwrite <br />
<br />
=== Troubleshooting ===<br />
<br />
* If you get <br />
KUniqueApplication: Cannot find the D-Bus session server<br />
check if you can access the display, e.g. type<br />
xclock<br />
and see if a clock appears on the screen.<br />
<br />
* If you get something like<br />
Error: standard icon theme "oxygen" not found!<br />
<br />
ASSERT: "!isEmpty()" in file /home/kde-devel/qt-copy/include/QtCore/../../src/corelib/tools/qlist.h, line 245<br />
Aborted (core dumped)<br />
You need to install kdebase - see above. It is enough to install the "runtime" directory from kdebase.<br />
<br />
== Generating local API documentation ==<br />
Although the API documentation for KDE is available online at [http://api.kde.org api.kde.org], it is sometimes useful to have it on your own disk, for example when you want to use [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|KDevelop]] for browsing the documentation or when you are not able to be online all the time.<br />
<br />
Be aware that generating the API documentation can take several hours and takes almost half a gigabyte of diskspace.<br />
The generation is handled by a script in {{path|kdelibs/doc/api}}, you need <tt>doxygen</tt> to be able to run it. <br />
<br />
To build the API documentation for kdelibs, type the following:<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE/kdelibs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Repeat for other modules as desired.<br><br />
cd <module home><br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Another, even easier method involves downloading this [[Doxyfile]] to your local system. Then simply change directory to where you want to create the documentation and run<br />
<code bash><br />
% doxygen /path/to/Doxyfile<br />
</code><br />
Then review the file {{path|doxygen.log}} to see the doxygen errors and warnings. You'll find the actual documentation in the {{path|apidocs}} subdirectory.<br />
<br />
== Staying up to date ==<br />
<br />
In order to keep the kde4 installation up to date, each of the modules installed should be updated periodically. As Monday is the day for big changes in kdelibs, Tuesday may be the best day to do this. For each module checked out, run <tt>svn up</tt> and <tt>make</tt>.<br />
<br />
For example:<br />
<code bash><br />
cs kdesupport # cs is not a typo<br />
svn up<br />
cb # cb is not a typo<br />
make -j2 VERBOSE=1 && make install<br />
</code><br />
<br />
Note: it is not necessary to run cmakekde for updates.<br />
<br />
== Installing a subset of a module ==<br />
<br />
Many modules in KDE contain a large number of programs which could take a long time to download and compile. In cases where you want to work only on a particular program or programs in a module, it is possible to download and compile particular folders. In some cases, certain folders are required for any build of the module. This is determined in the CMakeLists.txt file of the module. For example the [http://websvn.kde.org/branches/KDE/4.0/kdegames/CMakeLists.txt?view=markup kdegames CMakeLists.txt file] lists:<br />
<br />
<code><br />
add_subdirectory(libkdegames)<br />
add_subdirectory(libkmahjongg)<br />
<br />
macro_optional_add_subdirectory(doc)<br />
macro_optional_add_subdirectory(lskat)<br />
macro_optional_add_subdirectory(katomic)<br />
</code><br />
<br />
So, the libkdegames and libkmahjongg directories are required to build any of kdegames. The cmake directory will also usually be required. All the other directories (doc, katomic etc) are optional. They will be built if present on your machine. In this example, we build kmahjongg and kbattleship:<br />
<br />
<code bash><br />
cs KDE<br />
svn co -N kdegames # The -N switch performs a non-recursive checkout<br />
cd kdegames<br />
svn up libkdegames # Get required directories<br />
svn up libkmahjongg<br />
svn up cmake<br />
svn up kbattleship # Get optional directories<br />
svn up kmahjongg<br />
cmakekde <br />
</code><br />
<br />
== General troubleshooting ==<br />
<br />
What can happen over time, after some <tt>svn up</tt> commands, is that some of the tools used in the KDE build chain change their output format. For example, <tt>kcfg</tt> files are read by <tt>kconfig_compiler</tt> to produce configuration dialogs. CMake cannot detect those changes, and the compilation might fail. A workaround is to always force a re-generation of all such files:<br />
find $KDE_SRC/KDE/kdebase -name "*.kcfg" | xargs touch<br />
The same applies to <tt>ui</tt> files as produced by Qt designer.<br />
<br />
=== Locked sessions ===<br />
When installing KDE 4 as a user, one will not be able to unlock a locked session. To work around this issue you can either:<br />
su chown root.root $KDEDIR/lib/kde4/libexec/kcheckpass<br />
or<br />
chmod 755 $KDEDIR/lib/kde4/libexec/kcheckpass<br />
<br />
Also you have to add a "kde" service in /etc/pam.d/ folder<br />
<br />
For example for RH/Fedora based distros:<br />
<code> <br />
#%PAM-1.0<br />
auth include system-auth<br />
account include system-auth<br />
password include system-auth<br />
session include system-auth<br />
</code><br />
<br />
== Success! ==<br />
<br />
You are now ready to start building other svn modules in the same fashion as you built kdebase, running and testing KDE4 or writing your own patches and applications.<br />
<br />
See the [[Getting Started/Set up KDE 4 for development|Set up KDE 4 for development]] tutorial for how to start KDE 4 applications and how to use KDevelop to work on them.<br />
<br />
[[Category:Build KDE]]<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Archive:Getting_Started/Build/KDE4_(zh_CN)&diff=19240Archive:Getting Started/Build/KDE4 (zh CN)2008-01-06T15:44:23Z<p>Powerfox: /* 选项2:作为root用户 */</p>
<hr />
<div><!--Huanzhou Zhu初稿,Liang Qi整理!--><br />
{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4}}<br />
{{TutorialBrowser|<br />
<br />
series=开始|<br />
<br />
name=从源代码构建KDE4|<br />
<br />
pre=[[../../Sources/Anonymous_SVN|Anonymous SVN Quickstart Guide]]|<br />
<br />
next=[[../../Set_up_KDE_4_for_development_%28zh_CN%29|启动KDE4环境和应用程序]]|<br />
<br />
reading=[http://kdesvn-build.kde.org/ kdesvn-build: The KDE From Subversion Build Tool]<br>[[../../Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br>[[Development/Tutorials/CMake_(zh_CN) |CMake介绍]]<br>[[../KDE4/FreeBSD_(zh_CN)|FreeBSD备注]]<br>[[../KDE4/Mac OS X|Instructions for Mac OS X]]|<br />
}}<br />
<br />
== 摘要 ==<br />
<br />
这份教程介绍了一种使KDE运行于Linux/BSD系统的方法。这份教程通篇使用了bash shell。如果你对在其他系统(如:Solaris、MacOS或Microsoft Windows)上构建KDE有兴趣, 请访问[[../|构建]]页面并在最下方的链接处选择相应的操作系统。<br />
<br />
{{note|当周一提交了重大的修改时,构建错误的风险会很大。可以通过[http://developer.kde.org/~dirk/dashboard/ Dashboard]报告意料之外的破坏。非常欢迎大家修复失败的模块。<br />
}}<br />
<br />
== 所需软件 ==<br />
<br />
首先你必须安装以下软件,你才能成功完成这份教程:<br />
* 来自gcc项目的gcc和g++, 最好是4.1或更高的版本。<br />
* svn(Subversion客户端)<br />
* pkg-config<br />
* X11和OpenGL的开发库及头文件<br />
* libjpeg、libpng、libungif、libxml2和libxslt的开发库及头文件<br />
* makeobj脚本。可以做为kdesdk-scripts(debian)或类似的软件包的部件来安装,或者直接从[http://websvn.kde.org/trunk/KDE/kdesdk/scripts/makeobj?revision=600932&view=markup WebSVN]下载该软件本身。<br />
* shared-mime-info软件包,是KDE现在使用的freedesktop MIME标准。<br />
<br />
你也许还需要安装以下软件:<br />
* bash<br />
<br />
== 为KDE4开发创建一个用户账户 ==<br />
<br />
{{Note|<br />
一些人喜欢为KDE 4使用一个单独的用户帐户(例如一个旧的bug可能会误删除文件),并且后面的这些指令都是以这种方式进行的。<br />
<br />
使用一个单独的用户帐户做任何事情都是很有效率的,有关细节请参考[[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]。<br />
<br />
你还可以遵循下面的指令,但并不把这些环境变量保存到你的<tt>.bashrc</tt>中,请把他们放到一个单独的文件中,以备你在切换到KDE 4环境时使用。<br />
}}<br />
<br />
=== 选项1:命令行 ===<br />
<code bash><br />
useradd -m kde-devel<br />
</code><br />
或者:<br />
<code bash><br />
useradd kde-devel<br />
mkdir /home/kde-devel<br />
passwd kde-devel<br />
chown kde-devel:kde-devel /home/kde-devel 2>/dev/null || \<br />
chown kde-devel:users /home/kde-devel<br />
</code><br />
<br />
=== 选项2:使用KControl ===<br />
<br />
如果你已经安装了KDE3,你可以使用KDE控制中心里的用户管理模块来替代上述的命令添加用户。<br />
<br />
=== 设置环境 ===<br />
<br />
从你的普通账户下拷贝{{path|~/.bashrc}}到新的kde-devel账户下。然后,把[[Getting Started/Increased Productivity in KDE4 with Scripts/.bashrc|.bashrc示例]]的内容复制并且粘贴到{{path|~kde-devel/.bashrc}}。如果你不能使用<tt>makeobj</tt>命令,请把例子中的<tt>alias make=makeobj</tt>这一行注释掉,这一行命令来自于KDE SDK脚本。<br />
<br />
这样就可以访问本教程中所使用的如<tt>cmakekde</tt>这类命令,同时保证了Qt、KDE、CMake文件的正确的路径。<br />
<br />
更多的信息,请阅读[[Getting Started/Increased Productivity in KDE4 with Scripts]]。<br />
<br />
=== 切换到新用户 ===<br />
切换到用户kde-devel:(不要忘了输入横线)<br />
<code bash><br />
su - kde-devel<br />
</code><br />
<br />
在以下教程中将假定你使用<tt>kde-devel</tt>用户。<br />
<br />
== 开发用户的shell ==<br />
<br />
在有些系统上,新用户被默认配置使用{{path|/bin/sh}}。如果你的系统不是这样,请跳过这一节。使用{{path|/bin/sh}}非常不方便,你可能希望转换到{{path|/bin/bash}}或其他的shell。<br />
<br />
=== 选项1:作为kde-devel用户 ===<br />
<br />
如果你没有root特权,同时你的系统支持使用<tt>chsh</tt>程序来转换你自己的shell,那你可以尝试使用这条命令来把你的shell转换到{{path|/bin/bash}}:<br />
<code bash><br />
chsh -s /bin/bash kde-devel<br />
</code><br />
<br />
=== 选项2:作为root用户 ===<br />
<br />
如果你的系统带有<tt>usermod</tt>程序,你可以以root身份运行以下命令:<tt>usermod -s /bin/bash kde-devel</tt>。另一个选择是以root身份使用<tt>vipw</tt>程序安全的编辑你的{{path|/etc/passwd}}。在文件中找到“kde-devel”,将行尾的“{{path|/bin/sh}}”改为“{{path|/bin/bash}}”。保存你的修改并退出。<br />
<br />
新的shell将在你再次使用kde-devel用户登录时自动启动。<br />
<br />
== D-Bus ==<br />
QtDBus和KDE使用的D-Bus版本为0.62、0.92或更高的版本。0.60和0.61版可能也行但未经测试。0.90和0.91版不能工作。我们建议使用1.0版(最低0.94),所以如果你还没有该版本,请考虑升级。<br />
<br />
如果你已经使用了最新的D-Bus版本或者根本不想升级,可以跳过这一节。<br />
<br />
在运行秘诀中的步骤之前,请确认你有X11的头文件和库文件。配置脚本的第五行应该输出:<br />
Building X11 code: yes<br />
<br />
=== 秘诀 ===<br />
<br />
{{tip|请确认你的环境已按照[[Getting_Started/Build/KDE4#Setting_up_the_environment|上面]]的叙述正确配置。这对<tt>cs</tt>和<tt>cb</tt>函数的正确运行是必须的。}}<br />
<br />
<!--'cs'和'cb'不是拼写错误!--><br />
<code bash><br />
cs<br />
wget http://dbus.freedesktop.org/releases/dbus/dbus-1.0.2.tar.gz<br />
tar -xvzf dbus-1.0.2.tar.gz<br />
cd dbus-1.0.2/<br />
./configure --prefix=$DBUSDIR --localstatedir=$KDEDIR/var<br />
make<br />
make install<br />
dbus-uuidgen --ensure<br />
</code><br />
<br />
=== 发生了什么 === <br />
在切换到源码目录后(第1行),从freedesktop.org下载D-Bus的源代码(第2行)并解压缩(第3行)。在进入新创建的D-Bus目录后(第4行),通过提供的{{path|configure}}脚本准备构建(第5行)。在完成D-Bus的构建(第5行)和安装(第7行)后,使用<tt>dbus-uuidgen</tt>工具来安装机器识别文件,该文件使得D-Bus在桌面启动时自动运行(第8行)。<br />
<br />
注意,最后两步,你需要有对{{path|/var}}的写入权限,如果你的系统不支持sudo,你可以使用<tt>su</tt>命令代替。例如:<tt>su -c "make install"</tt>。<br />
<br />
== CMake ==<br />
如果你的[http://cmake.org/ CMake]>=2.4.5,那请跳过这一节。你可以直接使用[http://www.cmake.org/HTML/Download.html CMake网站]提供的二进制包。这里有针对一些发行版特定的安装包。针对openSUSE的CMake二进制包是由[http://software.opensuse.org/download/devel:/tools:/building/ openSUSE构建服务]提供的。<br />
<br />
=== 秘诀 ===<br />
<!--'cs'和'cb'不是拼写错误!--><br />
<code bash><br />
cs<br />
wget http://www.cmake.org/files/v2.4/cmake-2.4.6.tar.gz<br />
tar zxf cmake-2.4.6.tar.gz<br />
mkdir cmake-build<br />
cd cmake-build<br />
../cmake-2.4.6/bootstrap<br />
make<br />
sudo make install<br />
</code><br />
<br />
=== 发生了什么 ===<br />
首先,我们回到<tt>kde-devel</tt>用户的源码目录(第1行),获取CMake的源码(第2行)并解压(第3行)。然后创建一个CMake的构建目录(第4行)并进入该目录(第5行)。通过运行CMake的boostrap脚本来准备CMake的构建(第6行),然后以root身份编译(第7行)并安装(第8行)CMake。<br />
<br />
如果你的系统没有<tt>sudo</tt>命令,可以使用<tt>su -c "make install"</tt>命令代替。<br />
<br />
== Qt ==<br />
下一步,我们需要从KDE的代码仓库获得Qt4。KDE保证可以依赖任何版本的Qt 4.3来构建。Qt 4.2和之前的版本将不被支持且无法工作。Qt 4.3尚未发行,因此不一定有针对你的发行版的预编译包。你应该使用KDE Subversion服务器提供的代码副本。<br />
<br />
=== 秘诀 ===<br />
<code bash><br />
cd<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/qt-copy<br />
cd qt-copy<br />
./apply_patches<br />
./configure -qt-gif -no-exceptions -debug -fast \<br />
-prefix $QTDIR -qdbus -pch -nomake examples \<br />
-nomake demos<br />
make sub-src sub-tools<br />
# make install: only if QTDIR is not the current directory!<br />
make install <br />
</code><br />
<br />
=== 发生了什么 ===<br />
我们切换回<tt>kde-devel</tt>用户的主目录(第1行),然后使用subversion(svn)从KDE的代码仓库下载源代码(第2行)。在切换进入{{path|qt-copy}}目录后(第3行),我们运行{{path|qt-copy}}下脚本来管理补丁(第4行)。<br />
<br />
当这些补丁被应用后,我们使用<tt>configure</tt>脚本准备构建环境(第5-7行),这里使用的几行命令和选项在{{path|qt-copy/README.qt-copy}}文件里有解释。最后,编译我们构建KDE所需的最少需求组件(第8行)并安装Qt(第9-10行)。如果想要全部的例子和demo应用,你可以单独构建他们或直接在{{path|qt-copy}}目录下运行<tt>make</tt>。<br />
<br />
注意这次安装并不需要root,因为它把Qt安装到了本地的{{path|$QTDIR}}。所以,这次安装只要{{path|$QTDIR}}和{{path|$HOME/qt-copy}}不同即可,如果你已经遵循并执行了上面的指令,就不会出现这种情况。<br />
<br />
=== 疑难解答 ===<br />
如果你得到了“error: X11/Xlib.h: No such file or directory”,请安装<tt>xorg</tt>(实际的名称可能根据操作系统的不同而改变,例如在基于Ubuntu的系统Kubuntu上,这个包叫<tt>xorg-dev</tt>)的开发包。<br />
<br />
如果你在configure时获得缺失定义的错误,请检查<tt>$QMAKESPEC</tt>的值。一些发行版将这个值设置为系统安装的Qt,如果<tt>unset QMAKESPEC</tt>可以解决这个问题,你可能希望把它添加到<tt>~/.bashrc</tt>脚本中。<br />
<br />
如果你得到错误“.pch/debug-shared/QtCore”,这是因为Qt 4.3激活了你的gcc所支持的一些预编译头文件,但因为一些原因它不能为你工作。如果你使用distcc,使用-no-pch来配置Qt。如果你使用icecream,请从其svn主分支升级到最新版本。<br />
<br />
如果你的gcc支持,Qt4.3允许使用预编译的头文件,但因为某些原因它不工作。如果你使用distcc,使用 -no-pch来configure Qt.如果你使用icecream,从svn上升级到最新的版本。<br />
<br />
尝试运行一些Qt程序,比如{{program|assistant}}。如果它在QSpanData::adjustSpanMethods崩溃,那你可能使用了oxygen风格。尝试删除{{path|/lib/kde4/plugins/styles/kstyle-oxygen.so}}和{{path|/lib/kde4/plugins/styles/oxygen.so}}。当然,如果它们存在的话。<br />
<br />
== Strigi ==<br />
<br />
{{warning|如果你没有阅读[[Getting_Started/Build/KDE4_(zh_CN)#设置环境|设置环境]]而直接跳到这里的话,'''那下面提供的秘诀将无法工作'''。<br />
<br />
秘诀没有错误,<tt>cs</tt>和<tt>cb</tt>也没有排版错误。为了这份教程可以正确的工作,你'''需要'''根据这些指令正确设置你的环境。}}<br />
<br />
获取文件元数据(file metadata)的代码现在依赖于Strigi。要安装Strigi,你需要libz、libbz2、openssl(libcrypto或者libssl)、libclucene(>=0.9.16)以及libxml2或libexpat的库和头文件。<br />
<br />
=== 秘诀 ===<br />
<!--'cs'和'cb'不是拼写错误!--><br />
<code bash><br />
cs<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/kdesupport/strigi<br />
cd strigi<br />
cmakekde<br />
</code><br />
<br />
=== 发生了什么 ===<br />
先切换到源码的根目录下(第1行)。使用subversion下载Strigi的源代码(第2行),进入新的{{path|~/src/strigi}}目录(第3行),开始构建(第4行)。这将使我们在构建完成后仍留在Strigi的构建目录里。<br />
<br />
== kdelibs ==<br />
<br />
构建好Qt4和Strigi之后,我们现在可以开始构建KDE的基础库了,如果你使用了上述的[[Getting Started/Increased Productivity in KDE4 with Scripts/.bashrc|.bashrc]],里面就会有那些新的功能。<br />
<br />
=== 秘诀 ===<br />
<!--'cs'和'cb'不是拼写错误!--><br />
<code bash><br />
cd $KDE_SRC<br />
mkdir KDE && cd KDE<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdelibs<br />
cd kdelibs<br />
cmakekde<br />
</code><br />
<br />
{{tip|如果命令失败,并提示“CMake requires an out of source build directory”,请移除~/src/KDE/kdelibs/CMakeCache.txt,然后再次尝试。}}<br />
<br />
{{tip|如果<tt>cmakekde</tt>还输出同样的错误,那试试这个:<br />
<code bash><br />
cd<br />
cmake -DCMAKE_INSTALL_PREFIX=$KDEDIR \<br />
-DCMAKE_BUILD_TYPE=debugfull DKDE4_BUILD_TESTS=ON \<br />
~/src/KDE/kdelibs<br />
make<br />
make install<br />
</code>}}<br />
<br />
=== 发生了什么 ===<br />
我们先进入源文件的根目录(第1行),然后执行make并进入KDE目录(第2行)。使用subversion下载kdelibs的源码(第3行),进入新的{{path|~/src/KDE/kdelibs}}目录(第4行),并开始构建(第5行)。这将使我们在构建完成后仍留在kdelibs的构建目录里。<br />
<br />
{{tip|在这里你的系统上可能会缺少某些依赖关系!可以通过<tt>cmakekde</tt>的输出观察到这些缺少的依赖关系。你可能希望先执行<tt>cmake ~/src/KDE/MODULE_NAME</tt>来编译一些kde模块(比如kdelibs、kdepimlibs等)}}<br />
<br />
=== 附加的KDE特有CMake模块 ===<br />
在{{path|kdelibs/cmake/modules/}}中有一些构建KDE4应用所需的附加CMake模块,它们会随kdelibs同时安装。<br />
<br />
=== 疑难解答 ===<br />
如果你在编译kdelibs时遇到问题,请先确认[[Getting_Started/Build/KDE4_(zh_CN)#所需软件|所需软件]]中提到的软件是否已能正确安装运行。其他的可能包括:<br />
* 如果你得到错误信息说“Please create a separate build directory and run 'cmake path_to_kdelibs [options]' there.”,那么你需要在运行cmakekde之前改变你的构建目录(例:<tt>cs KDE/kdelibs && cb && cmakekde</tt>)<br />
* 如果找不到Qt或者找到了错误版本的Qt,请确认路径中的第一个qmake就是你需要的qmake。<br />
* 如果还是有问题,尝试CMake make-option <tt>--keep-going</tt>。<br />
* 这里你需要libungif库,不然你将得到象这样的错误信息“<tt>Could NOT find GIF</tt>”。<br />
* Qt-4.3升级:如果你在kjsembed中得到关于QScriptEngine的链接错误,编辑kdelibs中的CMakeCache.txt并移除关于QT_QTUITOOLS_LIBRARY的那些行,然后再次输入make(这个静态库有新的依赖关系,需要运行cmake的代码添加它运行所需要的依赖)。<br />
<br />
== kdepimlibs ==<br />
在<tt>kdelibs</tt>之后,''kdebase''之前,你需要构建和安装''kdepimlibs''。<br />
<br />
=== 秘诀 ===<br />
<!--'cs'和'cb'不是拼写错误!--><br />
<code bash><br />
cs KDE<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdepimlibs<br />
cd kdepimlibs<br />
cmakekde<br />
</code><br />
<br />
=== 发生了什么 ===<br />
我们先进入KDE源码目录(第1行)。使用subversion下载kdepimlibs的源码(第2行),进入新的{{path|~/src/KDE/kdepimlibs}}目录(第3行),并开始构建(第4行)。这将使我们在构建完成后仍留在<tt>kdepimlibs</tt>的构建目录里。<br />
<br />
== kdebase ==<br />
一些kioslaves需要kdebase。<br />
<!--'cs'和'cb'不是拼写错误!--><br />
<code bash><br />
cs KDE<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdebase<br />
cd kdebase<br />
cmakekde<br />
</code><br />
=== 疑难解答 ===<br />
如果你在编译kdebase时遇到问题:<br />
* 请确认你安装了<tt>libxss的头文件</tt>。(如果你没有这些头文件,通常你会得到“undefined references on xscreensaver objects”)<br />
* 那个<tt>meinproc</tt>必须放到{{path|/home/kde-devel/kde/bin/meinproc}}<br />
* 如果cmakekde无法找到kdepimlibs的路径,请编辑{{path|$KDE_BUILD/kdebase/CMakeCache.txt}}并手工设置<tt>KDEPIMLIBS_INCLUDE_DIR:PATH=$KDE_BUILD/kdepimlibs</tt><br />
* 如果你得到错误说“Please set the following variables: X11_XTest_LIB(ADVANCED)”, 请安装<tt>Xtst</tt>的开发包。有些系统上,这个包独立于<tt>xext</tt>,并取名为<tt>x11proto-xext-dev</tt>或者<tt>libxtst-dev</tt>。在安装完软件包后,你可能需要移除构建目录下的CMakeCache.txt。<br />
* 和“X11_Xinerama_LIB (ADVANCED)”一样,你需要安装<tt>xinerama</tt>的开发包<br />
* 如果你得到错误说“Please set the following variables: FONTCONFIG_INCLUDE_DIR, FONTCONFIG_LIBRARIES (ADVANCED)”,那么你需要安装libfontconfig。<br />
<br />
== 生成本地API文档 ==<br />
尽管我们在[http://api.kde.org api.kde.org]上提供了KDE的API文档,在你的硬盘上保存一份副本往往也是有必要的,例如你想要通过[[Getting_Started/Set_up_KDE_4_for_development#KDevelop|KDevelop]]浏览这些文档或你无法上网时。<br />
<br />
注意,生成API文档需要几个小时并占用差不多500M的磁盘空间。文档的生成通过{{path|kdelibs/doc/api}}下的一个脚本完成,运行这个脚本你需要<tt>doxygen</tt>。<br />
<br />
为了构建kdelibs的API文档,请输入下列命令:<br />
<!--'cs'和'cb'不是拼写错误!--><br />
<code bash><br />
cs KDE<br />
mkdir apidox<br />
cd apidox<br />
../kdelibs/doc/api/doxygen.sh ../kdelibs/<br />
</code><br />
<br />
== 成功了! ==<br />
你现在可以使用构建kdebase一样的方法构建其他svn模块,运行并测试KDE4或者编写你自己的补丁和应用程序。<br />
<br />
关于如何在你的新的KDE4环境下开始工作,请阅读[[Getting Started/Set up KDE 4 for development#Nested_KDE_4_session|Starting a KDE4 Environment and Applications]]。<br />
<br />
[[Category:Build KDE]]<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4&diff=19234Getting Started/Build/KDE42008-01-06T15:40:24Z<p>Powerfox: /* Option 2: As the root user */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Getting Started|<br />
<br />
name=Building KDE4 From Source|<br />
<br />
pre=[[../../Sources/Anonymous_SVN|Anonymous SVN Quickstart Guide]]|<br />
<br />
next=[[../../Set_up_KDE_4_for_development|Set up KDE 4 for development]]|<br />
<br />
reading=[[../kdesvn-build|kdesvn-build: The KDE From Subversion Build Tool]]<br>[[../../Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br>[[Development/Tutorials/CMake |Introduction to CMake]]<br>[[../KDE4/FreeBSD|FreeBSD notes]]<br>[[../KDE4/Mac OS X|Instructions for Mac OS X]]<br>[[../KDE4/Windows|Instructions for MS Windows]]|<br />
}}<br />
<br />
== Abstract ==<br />
<br />
This tutorial shows one way to get KDE from trunk running on Linux/BSD systems. There are also tutorials for [[Getting_Started/Build/KDE4/FreeBSD|FreeBSD]], [http://www.kdelibs.com/ Windows], [[Getting_Started/Build/KDE4/Mac OS X|Mac OS X]] and [http://solaris.kde.org/ Solaris]. Throughout the tutorial the bash shell is used.<br />
<br />
{{warning|Expect a higher risk of build failure '''on Mondays''' when most kdelibs changes are committed. [http://developer.kde.org/~dirk/dashboard/ Dashboard] reports unexpected breakages. You are encouraged to fix failing modules.<br />
}}<br />
<br />
== Software Requirements ==<br />
<br />
The following needs to be installed to successfully use this tutorial:<br />
* gcc and g++, preferably version 4.2 or higher<br />
* svn, the subversion revision control client<br />
* pkg-config<br />
* development libraries and headers for X11, OpenGL (mesa-common-dev and libglu1-mesa-dev), libjpeg, libpng, libungif, [http://clucene.sourceforge.net/index.php/Downloads libclucene], [http://download.librdf.org/source/ librdf], libxml2 and libxslt<br />
* the <tt>makeobj</tt> script, which is included in kdesdk. You can install it from kdesdk (kdesdk-scripts on Debian) or similar packages, or download at [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/makeobj WebSVN]<br />
* the [http://freedesktop.org/wiki/Software/shared-mime-info shared-mime-info package], is the freedesktop MIME standard now used in KDE<br />
* [http://boost.org/ boost], used by kdebase; after build and/or install, in order to make cmake aware about its location (FindBoost), add the boost directory (which contains the include subdirectory) to CMAKE_INCLUDE_PATH or set a environment variable called BOOST_ROOT that points to the boost directory.<br />
<br />
=== Ark Linux ===<br />
In Ark Linux, the build dependencies you need are installed with:<br />
<br />
<code bash><br />
apt-get install devel-core libxml-devel libxslt-devel bzip2-devel \<br />
clucene-core-devel librdf-devel shared-mime-info xorg-Mesa-libGL-devel \<br />
subversion boost-devel doxygen giflib-devel dbus-devel openssl-devel \<br />
alsa-lib-devel kdesdk-scripts qt4-devel<br />
</code><br />
<br />
If you prefer a graphical interface, select the packages listed above in the "Install Software" tool in Mission Control.<br />
<br />
This includes installation of CMake, DBus and Qt - you can skip steps 5, 6 and 7.<br />
<br />
=== Arch Linux ===<br />
In Arch Linux you need to install the following packages:<br />
<br />
<code bash><br />
pacman -Sy subversion bzip2 libxslt libxml2 \<br />
shared-mime-info mesa boost dbus openssl \<br />
pkgconfig xine-lib clucene<br />
</code><br />
<br />
If you want to use qt4 from the Arch Linux repository you can install it with:<br />
<code bash><br />
pacman -Sy qt4<br />
</code><br />
("pacman -Sy qt" if you are running bleeding-edge Arch Testing)<br />
<br />
<s>For clucene libraries you need the [http://aur.archlinux.org/packages.php?do_Details=1&ID=5968 PKGBUILD] from AUR.</s><br />
(No longer needed since clucene has been put into the extra-repo.)<br />
<br />
=== Fedora ===<br />
<br />
Some of the required packages for building KDE4 on Fedora 7 or higher:<br />
<br />
<code bash><br />
yum install clucene-core-devel libxml-devel libxslt-devel \<br />
dbus-devel boost-devel bzip2-devel openssl-devel alsa-lib-devel \<br />
redland-devel rasqal-devel raptor-devel hspell-devel aspell-devel \<br />
cups-devel xine-lib-devel avahi-devel gamin-devel OpenEXR-devel \<br />
enchant-devel jasper-devel ilmbase-devel pcre-devel gpgme-devel \<br />
libxklavier-devel glib-devel libusb-devel libsmbclient-devel \<br />
libxcb-devel NetworkManager-devel lm_sensors-devel libraw1394-devel \<br />
bluez-libs-devel gcc-c++ libXext-devel cmake subversion giflib-devel \<br />
libpng-devel libXdamage-devel libXcomposite-devel libXrender-devel \<br />
fontconfig-devel libXft-devel libXcursor-devel libXfixes-devel \<br />
ruby-devel libXScrnSaver-devel libkdcraw-devel exiv2-devel \<br />
lcms-devel libtiff-devel sqlite-devel libxkbfile-devel \<br />
imlib2-devel patch gstreamer-plugins-base-devel<br />
</code><br />
<br />
Some optional packages for koffice support:<br />
<code bash><br />
yum install qca2-devel gsl-devel freeglut-devel \<br />
GraphicsMagick-c++-devel GraphicsMagick-devel<br />
</code><br />
<br />
This includes installation of D-Bus and CMake -- you can skip steps 5 and 6.<br />
<br />
DCH-10/15/07: Note - It may be simpler to spin RPMs. Note that you can edit the variables in /etc/rpm/macros.kde4 (which is provided by Rawhide kde-filesystem).<br />
<br />
The build stage then looks like:<br />
(but in what directory?)<br />
%build<br />
<br />
mkdir -p %{_target_platform}<br />
<br />
pushd %{_target_platform}<br />
<br />
%{cmake_kde4} ..<br />
<br />
popd<br />
<br />
make %{?_smp_mflags} -C %{_target_platform}<br />
<br />
I have had better results with creating a kdesupport rpm which means that you should not install the soprano and strigi rpms. YMMV<br />
<br />
telsh: On a Fedora 8 System I had to install "qt4-devel" too to have qmake.<br />
<br />
=== Kubuntu and Debian ===<br />
<br />
In Kubuntu 7.04 (Feisty) and Debian (Testing/Unstable) the build dependencies you need are installed with:<br />
<code><br />
sudo aptitude install build-essential cdbs debhelper cmake \<br />
libxml2-dev libxslt1-dev libbz2-dev libclucene-dev librdf-dev \<br />
shared-mime-info libgl1-mesa-dev libglu1-mesa-dev mesa-common-dev \<br />
libxext-dev libjpeg-dev libpng12-dev subversion libsm-dev libxinerama-dev \<br />
libxrender-dev libfontconfig-dev libboost-dev libxcursor-dev doxygen \<br />
libungif4-dev libdbus-1-dev libssl-dev libgpgme11-dev \<br />
libasound2-dev kdesdk-scripts libpth-dev libjasper-dev \<br />
ssh libxine-dev libqimageblitz-dev libqimageblitz4 libglib2.0-dev \<br />
libxkbfile-dev libenchant-dev libbluetooth-dev network-manager-dev \<br />
libsmbclient-dev libxcb1-dev libcaptury-dev libxcomposite-dev \<br />
libxdamage-dev libusb-dev libgpgme11-dev libldap2-dev<br />
</code><br />
<br />
In Kubuntu 7.10 (Gutsy) and Debian unstable you also have to add:<br />
<code><br />
sudo aptitude install dbus-x11 libqt4-dev libqca2-dev libeigen-dev \<br />
libstreamanalyzer-dev libsoprano-dev libstrigiqtdbusclient-dev \<br />
libxklavier11-dev libxml2-utils libdbus-1-dev libxslt1-dev cmake libbz2-dev \<br />
libungif4-dev libgpgme11-dev libboost-dev libxine-dev libxkbfile-dev<br />
</code><br />
<br />
For a fully functional API documentation framework you also need:<br />
<code><br />
sudo aptitude install graphviz<br />
</code><br />
<br />
There is no need to compile qt or kdesupport on kubuntu gutsy. All required packages are provided by installing the above. Setup the kde4 user etc as explained in the next section, but skip over compiling qt, hal and kdesupport.<br />
<br />
{{Note|<br />
If you get something trouble on compile KDE4<br />
Beta4 or above in Kubuntu 7.10, such as :<br />
<br />
Soprano version is too low<br />
<br />
strigi xxx.h not found...<br />
<br />
You may need to checkout, and compile the relevant part of<br />
kdesupport source code in the SVN server of KDE4. (svn://anonsvn.kde.org/home/kde/trunk/kdesupport/soprano/) <br />
<br />
This is covered when you get to the section on compiling kdesupport.<br />
<br />
You might also have to remove any installed soprano package : sudo apt-get remove libsoprano4 libsoprano-dev<br />
<br />
If you still get an error in the kdelibs section about soprano like:<br />
CMake Error: Error in cmake code at<br />
$src/KDE/kdelibs/cmake/modules/FindSoprano.cmake:78:<br />
FILE Internal CMake error when trying to open file: /usr/include/soprano/version.h for reading.<br />
<br />
then delete kdelibs/CMakeCache.txt<br />
}}<br />
<br />
=== openSUSE ===<br />
<br />
In openSUSE 10.2 and newer, you can install packages using [http://en.opensuse.org/Zypper Zypper]:<br />
<code bash><br />
sudo zypper install <package-name><br />
</code><br />
<br />
In older releases of SUSE, you can use YaST:<br />
<code bash><br />
su<br />
yast -i <packagename><br />
</code><br />
<br />
'''Required Packages'''<br />
<br />
The packages you will need to install are:<br />
<code><br />
xorg-x11-devel<br />
libxml2-devel <br />
kdesdk3 <br />
clucene-core-devel <br />
boost-devel<br />
libjpeg-devel <br />
liblrdf-devel <br />
libpng-devel <br />
libxslt-devel <br />
libredland-devel<br />
Mesa-devel <br />
giflib-devel <br />
subversion <br />
gcc <br />
gcc-c++<br />
gmp-devel (needed to build kdesupport)<br />
gpgme-devel (needed to build kdepimlibs)<br />
libxine1-devel<br />
</code><br />
<br />
'''Optional Packages'''<br />
<br />
You can skip the manual and painful installation kdesupport and its dependencies ( Qt 4.3, CMake 2.4.6, DBus, Hal, clucene-core, Strigi,<br />
Soprano and other Nepomuk dependencies) by adding the KDE:KDE4 repository from<br />
the [http://download.opensuse.org/repositories/KDE:/KDE4/ openSUSE Build Service] to your installation sources. <br />
<br />
For openSUSE 10.2 and newer do:<br />
<code><br />
sudo zypper service-add http://software.opensuse.org/download/KDE:/KDE4/openSUSE_10.2 KDE4-102<br />
</code><br />
<br />
For older versions of SUSE Linux do:<br />
<code><br />
su<br />
installation_sources -a http://software.opensuse.org/download/KDE:/KDE4/[YOUR SUSE LINUX VERSION]<br />
</code><br />
<br />
Now install the following packages:<br />
<code><br />
cmake<br />
dbus-1-devel<br />
libqt4-devel<br />
libqca2-devel<br />
libsoprano-devel<br />
libqimageblitz-devel<br />
strigi<br />
strigi-ui<br />
</code><br />
<br />
There are a lot more packages that are needed to satisfy the config-check, such as libusb-devel, bison etc., so look out for the config notifications and install accordingly. Please remember to skip any instructions that refer to kdesupport below. Start to compile with kdelibs. <br />
<br />
And for fully functional apidox framework you also need:<br />
<code><br />
graphviz<br />
</code><br />
<br />
CMake binary packages for openSUSE are available from the KDE:KDE4 repository as well as from the [http://software.opensuse.org/download/devel:/tools:/building/ openSUSE build service].<br />
<br />
=== Gentoo ===<br />
<br />
==== Install by hand ====<br />
<br />
You can use stable ebuilds just remember to sync your portage before you begin.<br />
<br />
Remember: All commands are executed as root.<br />
<br />
Required:<br />
<br />
We need to allow the following keyword masked ebuilds.<br />
<br />
<code bash><br />
echo 'dev-util/cmake' >> /etc/portage/package.keywords<br />
echo 'dev-cpp/clucene' >> /etc/portage/package.keywords<br />
</code><br />
<br />
Make sure you have set the berkdb USE flag for redland, otherwise nepomuk won't work.<br />
<br />
<code bash><br />
echo 'dev-libs/redland berkdb' >> /etc/portage/package.use<br />
echo 'x11-libs/qt accessibility' >> /etc/portage/package.use<br />
</code><br />
<br />
These are the packages you will need to emerge, I included the update option into the emerge command so you will not re-emerge anything that you might already have installed.<br />
<br />
<code bash><br />
emerge -avu 'sys-devel/gcc' \<br />
'dev-util/subversion' \<br />
'dev-util/pkgconfig' \<br />
'x11-base/xorg-x11' \<br />
'virtual/glut' \<br />
'media-libs/mesa' \<br />
'media-libs/jpeg' \<br />
'media-libs/libpng' \<br />
'media-libs/giflib' \<br />
'dev-cpp/clucene' \<br />
'dev-util/cppunit' \<br />
'media-libs/liblrdf' \<br />
'dev-libs/libxml2' \<br />
'dev-libs/libxslt' \<br />
'x11-misc/shared-mime-info' \<br />
'dev-libs/boost' \<br />
'dev-util/cmake' \<br />
'dev-libs/redland' \<br />
'sys-apps/dbus' \<br />
'sys-apps/hal' \<br />
'x11-libs/qt'<br />
</code><br />
<br />
You will also need to emerge either 'kde-base/kdesdk' or kde-base/kdesdk-scripts'.<br />
<br />
If you emerged DBUS, CMAKE, QT or HAL you may skip those sections respectively.<br />
Good luck!<br />
<br />
==== Install via portage ====<br />
<br />
Also you can install the KDE 4 packages directly via <br />
<code bash><br />
emerge -a <packagename><br />
</code><br />
<br />
To get the things you need, [http://gentoo-wiki.com/TIP_Overlays#Layman install layman] and then pull in the "kde" overlay (which contains experimental KDE ebuilds): <br />
<code bash><br />
layman -a kde<br />
</code><br />
After this you need to adjust some USE-flags for KDE 4 and tell portage to use the testing KDE 4 ebuilds instead of the stable KDE 3 ones. <br />
<br />
That way portage will do the dependency tracking for you. <br />
<br />
Detailed instructions on building KDE 4 in Gentoo via portage can be found in the [http://overlays.gentoo.org/proj/kde/wiki KDE overlay wiki]. They are discussed in the forum thread [http://forums.gentoo.org/viewtopic-t-530111-postdays-0-postorder-asc-start-0.html KDE 4 monolithic ebuilds], which is continued [http://forums.gentoo.org/viewtopic-p-4359581.html#4359581 here]<br />
<br />
=== Mandriva ===<br />
In Mandriva the build dependencies you need are installed with:<br />
<br />
<code bash><br />
urpmi gcc-c++ cmake libxml2-devel libbzip2_1-devel \<br />
libclucene0-devel liblrdf2-devel libmesagl1-devel \<br />
subversion doxygen libdbus-1_3-devel libopenssl0.9.8-devel \<br />
libalsa2-devel libgpgme-devel libboost1-devel libxine-devel<br />
</code><br />
<br />
If you're running 64-bit environment you should replace all packages starting with "lib..." to "lib64...".<br />
<br />
If you prefer a graphical interface, select the packages listed above in the "Install Software" tool in Mandriva Linux Control Center.<br />
<br />
This includes installation of CMake, DBus - you can skip steps 5 and 6.<br />
<br />
== Create a user account for KDE4 development ==<br />
<br />
{{Note|<br />
Some people like to have a separate user account for KDE 4 (for instance an old bug deleted files by mistake), and the instructions below were written with that approach.<br />
<br />
However it is much more efficient to do everything with a single user account, see [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br />
for more details. <br />
<br />
You can still follow the instructions below, but don't put the environment variables in your <tt>.bashrc</tt>, put them in a separate file that you source to switch to the KDE 4 environment.<br />
}}<br />
<br />
=== Option 1: Command Line ===<br />
<code bash><br />
useradd -m kde-devel<br />
passwd kde-devel<br />
</code><br />
<br />
<br />
{{Warning|<br />
The new kde-devel user will not be added automatically to all the user groups, which will result in not having sound, not being able to sudo, etc. Edit your /etc/groups file to add the kde-devel user to all the groups that you need (probably the groups that your usual username is already assigned to).<br />
}}<br />
<br />
=== Option 2: Using KControl ===<br />
<br />
Instead of using the commands above, you can also use the User module in the KDE Control Center if you already have KDE3 installed.<br />
<br />
=== Setting up the environment ===<br />
<br />
Copy the {{path|~/.bashrc}} from your normal user account to the new kde-devel account. Next, copy and paste the contents of the [[Getting Started/Increased Productivity in KDE4 with Scripts/.bashrc|example .bashrc]] into {{path|~kde-devel/.bashrc}}. Be sure to comment out the line <tt>alias make=makeobj</tt> if you do not have the <tt>[[Getting Started/Build/KDE4#Required Software|makeobj]]</tt> command available. You will probably also want to modify the path to make sure it doesn't include your kde3 paths. Also if you want to use KDevelop to develop KDE 4 applications you may pass the ''-GKDevelop3'' flag to the ''cmake'' command (to make CMake generate KDevelop project files, it will help to avoid rebuilding in the future, see [[Getting_Started/Set_up_KDE_4_for_development#Setting_up_the_environment|this]]). <br />
To make it run, you have to open a new bash or to execute <br />
<code bash><br />
source ~/.bashrc<br />
</code><br />
<br />
This will provide access to commands such as <tt>cmakekde</tt> that are used in this tutorial as well as ensure that the proper paths are in place for Qt, KDE and CMake binaries.<br />
<br />
For more information, please read the [[Getting Started/Increased Productivity in KDE4 with Scripts]] tutorial.<br />
<br />
=== Switching to the New User ===<br />
Switch to the user kde-devel: (don't forget the dash)<br />
<code bash><br />
ssh -X kde-devel@localhost<br />
</code><br />
<br />
{{Note|<br />
If the ssh command fails, check out the [[Getting_Started/Set_up_KDE_4_for_development#Launching_KDE_4_apps|Launching KDE 4 apps]] section of the [[Getting_Started/Set_up_KDE_4_for_development|KDE4 development guide]].<br />
}}<br />
<br />
== The development user's shell ==<br />
<br />
On some systems a new user is configured by default to use {{path|/bin/sh}}. If this is not the case on your system, you can skip this section. Using {{path|/bin/sh}} can be very inconvenient to work with and you may want to change it to {{path|/bin/bash}} or another shell.<br />
On Ark Linux and Fedora, you can skip this step - {{path|/bin/sh}} is {{path|bash}}.<br />
<br />
=== Option 1: As the kde-devel user ===<br />
<br />
If you don't have root privileges and your system supports the changing of your own shell with the <tt>chsh</tt> application, then you could try to change your shell to {{path|/bin/bash}} by using:<br />
<code bash><br />
chsh -s /bin/bash kde-devel<br />
</code><br />
<br />
=== Option 2: As the root user ===<br />
<br />
If your system comes with the <tt>usermod</tt> application you can run the following command as root: <tt>usermod -s /bin/bash kde-devel</tt>.<br />
<br />
Another option is to use the <tt>vipw</tt> application as root to safely edit your {{path|/etc/passwd}}. Locate 'kde-devel' in the the file. Change '{{path|/bin/sh}}' at the end of the line to read '{{path|/bin/bash}}', save your changes and exit.<br />
<br />
The new shell will be started automatically when you log in as the kde-devel user again.<br />
<br />
== D-Bus ==<br />
QtDBus and KDE are known to work with D-Bus versions 0.62, as well as 0.92 and upwards. Versions 0.60 and 0.61 may work too but are not tested. Versions 0.90 and 0.91 are known not to work. We recommend using post-1.0 release versions (at least 0.94), so consider upgrading if you haven't done so.<br />
<br />
You may skip this section if you have a recent D-Bus version or if you don't want to upgrade. You probably want to skip building the bindings until/unless you know you will be building HAL (see below).<br />
<br />
Before running these steps in the recipe, make sure your X11 headers and libraries are available. The configure script run on line 5 of the following instructions should output:<br />
Building X11 code: yes<br />
<br />
=== The Recipe ===<br />
<br />
{{tip|Make sure you did set up your environment correctly as described [[Getting_Started/Build/KDE4#Setting_up_the_environment|above]]. This is necessary for the <tt>cs</tt> and <tt>cb</tt> functions to work.}}<br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]] <br />
wget http://dbus.freedesktop.org/releases/dbus/dbus-1.0.2.tar.gz<br />
tar -xvzf dbus-1.0.2.tar.gz<br />
cd dbus-1.0.2/<br />
./configure --prefix=$DBUSDIR --localstatedir=/var<br />
make<br />
sudo make install<br />
sudo dbus-uuidgen --ensure<br />
<br />
cs # see above<br />
wget http://dbus.freedesktop.org/releases/dbus-glib/dbus-glib-0.74.tar.gz<br />
tar -xvzf dbus-glib-0.74.tar.gz<br />
cd dbus-glib-0.74/<br />
./configure --prefix=$DBUSDIR<br />
make<br />
sudo make install<br />
cd<br />
sudo chown -R kde-devel:kde-devel *<br />
<br />
=== What's Happening === <br />
After changing into the source directory (line 1), D-Bus source code is downloaded from freedesktop.org (line 2) and unpacked (line 3). After going into the newly created D-Bus directory (line 4), the build is set up using the supplied {{path|configure}} script (line 5). After building (line 6) and installing (line 7) D-Bus, we use the <tt>dbus-uuidgen</tt> tool to install a machine identification file that allows the bus to start automatically when the desktop session starts (line 8).<br />
<br />
Note that you need write access to {{path|/var}} for the last two steps. If your system does not have the sudo command, you can use the <tt>su</tt> command instead, e.g. <tt>su -c "make install"</tt>.<br />
<br />
The steps for building the glib bindings are similar to the above.<br />
<br />
When these two packages are done building, we must fix the file ownership because 'sudo make install' has created root owned files and directories in ~kde-devel/kde.<br />
<br />
== CMake ==<br />
Skip this if you have [http://cmake.org/ CMake] >=2.4.5 installed. <br />
You should be able to directly use the binary packages available on the [http://www.cmake.org/HTML/Download.html CMake site]. There are also distribution specific packages available.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click Here to learn more]] <br />
wget http://www.cmake.org/files/v2.4/cmake-2.4.6.tar.gz<br />
tar -zxf cmake-2.4.6.tar.gz<br />
mkdir cmake-build<br />
cd cmake-build <br />
../cmake-2.4.6/bootstrap<br />
make<br />
sudo make install<br />
<br />
=== What's Happening ===<br />
First, we go back to the <tt>kde-devel</tt> user's source directory (line 1), get the CMake sources (line 2) and unpack them (line 3). We create a directory to build CMake in (line 4) and go into it (line 5). We then run the CMake bootstrap script to set up the CMake build (line 6), then make (line 7) and install it (line 8) using the root user.<br />
<br />
If your system does not have the <tt>sudo</tt> command, you can instead do <tt>su -c "make install"</tt>.<br />
<br />
== Qt ==<br />
Next we need to get Qt4. KDE is guaranteed to build against any Qt 4.3. Qt 4.2 and earlier are not supported and will not work. <br />
<br />
If your distribution has a recent version of Qt4, that should work. Most distros backport bugfixes, and some distros, like Debian or openSUSE, even use the patches from KDE svn. In other cases, using the recipe below will give you a more stable Qt than your distro. Refer to the distribution specific sections above for more information. <br />
<br />
As for now Qt3 compatibility layer in Qt 4 is mandatory, so please <b>avoid</b> using "-no-qt3support" option when building Qt4 from sources.<br />
<br />
=== The Recipe ===<br />
cd # Note: qt-copy lives in $HOME/qt-copy. See $QTDIR in [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|<font color=red>.bashrc</font>]] <br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/qt-copy<br />
cd qt-copy<br />
./apply_patches<br />
./configure -qt-gif -no-exceptions -debug -fast \<br />
-prefix $QTDIR -nomake examples -nomake demos<br />
make -j2<br />
<br />
# if we don't install, we'll just clear obj files to<br />
# save disk space<br />
if [ $QTDIR = `pwd` ]; then \<br />
find . -name '*.o' -delete ; \<br />
else make install; fi;<br />
<br />
=== What's Happening ===<br />
We switch back to the <tt>kde-devel</tt> user's home directory (line 1) and download the source code using subversion (svn) from KDE's repository (line 2). After changing into the resulting {{path|qt-copy}} directory (line 3), we run a script that manages the patches that come with <tt>qt-copy</tt> (line 4). <br />
<br />
Once the patches have been applied, we then set up the build using the <tt>configure</tt> script (line 5-6). The various command line options used are explained in the {{path|qt-copy/README.qt-copy}} file. Finally, we build the minimal requirements for KDE (line 7) and install (line 10) Qt. If install dir is the same as the current dir (line 8), then we just free some space (line 9) instead. If you want all the example and demo applications, you can either build them individually or simply do a <tt>make</tt> from the {{path|qt-copy}} directory. <br />
<br />
Note that the installation does not require root as it installs Qt locally into {{path|$QTDIR}}. Anyway, installation is only needed if {{path|$QTDIR}} differs from {{path|$HOME/qt-copy}}, which is not the case if you have exactly followed the instructions.<br />
<br />
=== Troubleshooting ===<br />
If you get "error: X11/Xlib.h: No such file or directory", install the devel package of <tt>xorg</tt> (the actual name may vary between operating systems, for example it is <tt>xorg-dev</tt> on Ubuntu based systems such as Kubuntu). <br />
<br />
If you get an error in the configure step about missing defines, check the value of <tt>$QMAKESPEC</tt>. Some distributions set this to point directly to the system-installed Qt. If <tt>unset QMAKESPEC</tt> solves the problem, you probably want to add it to the <tt>~/.bashrc</tt> script.<br />
<br />
If you get an error ".pch/debug-shared/QtCore", this is because Qt-4.3 enables precompiled headers if your gcc supports it, but for some reason it doesn't work for you. If you use distcc, configure qt with -no-pch. If you use icecream, update to the latest icecream from svn trunk.<br />
<br />
Try running any Qt program, like {{program|assistant}}. '''Note:''' You may need to run <tt>xhost +local:kde-devel</tt> as your regular kde3 user to run this application. If it crashes in QSpanData::adjustSpanMethods, then your problem is the oxygen style. Try removing {{path|lib/kde4/plugins/styles/kstyle-oxygen.so}} and {{path|lib/kde4/plugins/styles/oxygen.so}} if they exist in the KDE install prefix.<br />
<br />
== HAL ==<br />
<br />
{{tip|You can use qdbusviewer to see if you have org.freedesktop.hal. If not, you might need a newer version of hal. If you have org.freedesktop.hal, you probably don't need to, and don't ''want'' to, roll your own HAL.}}<br />
<br />
If your system requires you to build a newer version of HAL, there's a decent chance you'll need to build other stuff as well, some of which may not be straight forward. Since this should only be required for older distros, instructions are on [[Getting_Started/Build/HAL| a separate page]].<br />
<br />
== kdesupport ==<br />
<br />
{{warning|Don't forget to read the [[Getting_Started/Build/KDE4#Setting_up_the_environment|Setting Up The Environment]] section first.}}<br />
<br />
There are several libraries that KDE applications rely on in the kdesupport module. This includes Strigi and Soprano for file metadata and search, QImageBlitz for image manipulation needed in kdebase, eigen for visual effects in applications such as Kalzium, taglib for music players and qca for some cryptographic needs. <br />
<br />
Strigi itself has a few dependencies as well: you will need the libraries and headers for libz, libbz2, openssl (libcrypto or libssl), libclucene (>=0.9.16a but watch out: version 0.9.17 does '''not''' work), and either libxml2 or libexpat.<br />
<br />
Please remember that if you use openSUSE, you can install the needed packages from the KDE:KDE4 buildservice repository and do not have to bother with fiddling the details below. Skip to the kdelibs section. <br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/kdesupport/<br />
cd kdesupport<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1). We download the sources in kdesupport using subversion (line 2), go into the new {{path|~/kde/src/kdesupport}} directory (line 3), and commence the build (line 4). This will leave us in the kdesupport build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you get <br />
cmakekde: command not found<br />
then you have to go manually into the kdesupport directory in ~ and execute the command cmakekde. if this still doesn't work, then something is wrong with your bashrc.<br />
<br />
If you get <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 />
LIBXML2_INCLUDE_DIR (ADVANCED)<br />
you should install the development package for libxml2.<br />
<br />
If you get <br />
CMake Error: Could NOT find REDLAND<br />
then you need librdf from the Redland.<br />
If your distribution does not provide the librdf package, you can download the source there: [http://download.librdf.org/source/ http://download.librdf.org/source/] and build it.<br />
(Gentoo users: The ebuild for librdf is named dev-libs/redland)<br />
<br />
If you get<br />
Fetching external item into 'kdesupport/admin'<br />
Error validating server certificate for 'https://...'<br />
see [http://techbase.kde.org/Getting_Started/Sources/Using_Subversion_with_KDE Using Subversion with KDE]<br />
<br />
If you get<br />
FILE cannot create directory: /usr/lib[64]/qt4/plugins/crypto. Maybe need administrative privileges.<br />
<br />
make: *** [install] Error 255<br />
take a second look in the .bashrc file described above, are paths correct? ($QTDIR and $PATH are used to get the QT installation path)<br />
Alternatively, you may see this error if you decided to use a distribution installed version of qt4 and skipped the Qt install above. Either install qt-copy as describe above, or "sudo make install". If you use "sudo make install", make sure that you change the ownership back to your user for some of the ~/kde subdirectories that were effected by using sudo (ie. "<tt>sudo chown -R kde-devel:kde-devel ~/kde</tt>").<br />
<br />
If you get a message related to <br />
target libQtTest.so not found<br />
you may need to recompile qt-copy. This time you should take out<br />
-nomake demos -nomake examples<br />
from the configure command, so that Qt generates library QtTest.<br />
<br />
== kdelibs ==<br />
<br />
We can now move on to building KDE's base libraries.<br />
<br />
=== The Recipe ===<br />
cd <br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
mkdir KDE && cd KDE<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdelibs<br />
cd kdelibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1) then make and go into the KDE directory (line 2). We download the sources for kdelibs using subversion (line 3), go into the new {{path|~/kde/src/KDE/kdelibs}} directory (line 4), and commence the build (line 5). This will leave us in the <tt>kdelibs</tt> build directory after the build is completed.<br />
<br />
{{tip|There might be missing dependencies on your system! They are easily overlooked in the output of <tt>cmakekde</tt>.<br />
You might want to do a <tt>cmake $KDE_SRC/KDE/MODULE_NAME</tt> prior to compiling any kde modules (like kdelibs, kdepimlibs etc.)}}<br />
<br />
=== Additional KDE-specific CMake modules ===<br />
There are additional CMake modules in {{path|kdelibs/cmake/modules/}} that are necessary for building KDE4 applications. These will be installed for you when kdelibs itself is installed.<br />
<br />
=== Troubleshooting ===<br />
If you have problems compiling kdelibs, first make sure the software in the [[Getting_Started/Build/KDE4#Software_Requirements|Required Software]] section above is installed and works. Other possible hints include:<br />
* If the <tt>cmakekde</tt> command fails stating that CMake requires an out of source build directory, remove {{path|~/kde/src/KDE/kdelibs/CMakeCache.txt}}, and try again.<br />
<br />
If <tt>cmakekde</tt> still gives the same error then try this <br />
cd<br />
cmake -DCMAKE_INSTALL_PREFIX=$KDEDIR \<br />
-DCMAKE_BUILD_TYPE=debugfull \<br />
-DKDE4_BUILD_TESTS=ON \<br />
~/kde/src/KDE/kdelibs<br />
make<br />
make install<br />
* If you received an error stating "Please create a separate build directory and run 'cmake path_to_kdelibs [options]' there.", then you need to change to your build directory before running cmakekde. (e.g <tt>cs KDE/kdelibs && cb && cmakekde</tt>) If the message stays, run 'svn status' in the kdelibs directory and remove all files labeled with '?'.<br />
* If Qt wasn't found or the wrong version of Qt was found, make sure that the qmake from the Qt you need is the first qmake in the path.<br />
* If qmake wasn't found and you are using Debian packages, /usr/bin/qmake probably points to a wrong qmake version. To fix this run as root:<br />
update-alternatives --config qmake<br />
* If the problems persist, try the CMake make-option <tt>--keep-going</tt>.<br />
* Here you need the libungif library, otherwise you will get an error message like "<tt>Could NOT find GIF</tt>".<br />
* Qt-4.3 upgrade: if you get a link error in kjsembed talking about QScriptEngine, edit CMakeCache.txt in kdelibs and remove the lines that talk about QT_QTUITOOLS_LIBRARY, then type make again (that static library has a new dependency, and the cmake code that adds it needs to run).<br />
* if you get <code>CMake Error: KDE Requires Qt to be built with SSL support<br />
</code>, install openssl-devel, remove CMakeCache.txt and re-compile QT.<br />
* if you get <code>kdelibs/kimgio/ico.cpp:188: undefined reference to `QImage::jumpTable()'</code> it means you compiled QT without QT3 support(no, linking to a true QT3 install won't work)<br />
* if none of the errors above match yours, you might just try a quick'n'dirty <code>make clean</code> in kdelibs.<br />
<br />
== kdepimlibs ==<br />
After <tt>kdelibs</tt>, but before ''kdebase'', you need to build and install ''kdepimlibs''.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdepimlibs<br />
cd kdepimlibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We go into the KDE source directory (line 1), download the source code for kdepimlibs using subversion (line 2) and then go into the new {{path|~/kde/src/KDE/kdepimlibs}} directory (line 3). We then commence the build (line 4). This will leave us in the <tt>kdepimlibs</tt> build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you have trouble compiling kdepimlibs:<br />
* the cmakekde command may require a later version of the gpgme library. This is available from the project's web site: http://www.gnupg.org/(en)/download/index.html - please note that the build of gpgme also requires libgpg-error, also available from the same location. Both libraries are installed by the "./configure", "make" and "sudo make install" sequence, with the gpgme library configured with the additional "--with-gpg-error-prefix" parameter. You may need to overwrite your existing "/usr/bin/gpgme-config" file with the newer version for the kdepimlibs to pick up the new install.<br />
<br />
== kdebase ==<br />
kdebase is divided into three parts:<br />
* '''apps'''<br />
:This contains applications like Dolphin or KWrite.<br />
* '''runtime'''<br />
:This contains things needed by every application at runtime, like icons. It is a required dependency for each KDE application, so you have to compile and install this.<br />
* '''workspace'''<br />
:This contains things specific to the KDE desktop, like Plasma or the window manager. Most stuff here depends on X11. You only need it if you want to build a full KDE desktop.<br />
<br />
You can build all of kdebase at once, which is described in the recipe below. If you only want to build kdebase-runtime, which is the only requirement, you can replace <code bash>cd kdebase</code> with <code bash>cd kdebase/runtime</code> in the recipe below.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdebase<br />
cd kdebase<br />
cmakekde<br />
<br />
=== Troubleshooting ===<br />
If you have troubles compiling kdebase:<br />
* Make sure you have the <tt>libxss headers</tt> installed. (Usually you got undefined references on xscreensaver objects if you do not have those headers)<br />
* <tt>which meinproc</tt> has to deliver {{path|/home/kde-devel/kde/bin/meinproc}}<br />
* if cmakekde can not find the path of kdepimlibs, edit the file {{path|$KDE_BUILD/KDE/kdebase/CMakeCache.txt}} and manually set <tt>KDEPIMLIBS_INCLUDE_DIR:PATH=$KDE_BUILD/kdepimlibs</tt><br />
* if you get an error saying "Please set the following variables: X11_XTest_LIB (ADVANCED)", install the devel package of <tt>Xtst</tt>. On some systems, this is packaged separately from <tt>xext</tt> and called <tt>x11proto-xext-dev</tt> or <tt>libxtst-dev</tt>. You may also need to remove the CMakeCache.txt file in the build dir after installing the package.<br />
* the same for "X11_Xinerama_LIB (ADVANCED)" where you will need the devel package for <tt>xinerama</tt>.<br />
* if you get an error complaining about a missing variable X11_Xrandr_LIB, you need the devel package for libxrandr (libxrandr-devel on ubuntu-systems)<br />
* if you get the error "Please set the following variables: FONTCONFIG_INCLUDE_DIR, FONTCONFIG_LIBRARIES (ADVANCED)", then you need to install the libfontconfig headers<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: KMETADATA_LIBRARIES", you need to install soprano from kdesupport and to rebuild kdelibs<br />
* if you get the error "‘XserverRegion’ does not name a type" make sure you have libxcomposite headers installed (<tt>libxcomposite-dev</tt> in ubuntu)<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: QT_QTOPENGL_LIBRARY (ADVANCED) ", try editing CMakeCache.txt and setting QT_QTOPENGL_LIBRARY:FILEPATH=/home/kde-devel/qt-copy/lib/libQtOpenGL.so<br />
<br />
* if you get messages as "KDE4_INSTALL_HANDBOOK() is deprecated. Remove it please. Now all is done in KDE4_CREATE_HANDBOOK." then, either find the files containing the offending line and comment it out manually, or run the following script in ~/kde/src/KDE/kdebase: [http://www.plamadeala.com/files/macros_corrector.sh macros_corrector.sh]. It will just REMOVE the line that has "kde4_create_handbook" in it from all the found files.<br />
*If you get an error (in ubuntu) concerning libxtst.so install the libxtst-dev package<br />
* If you get the message "kdebase/workspace/kcontrol/kxkb/x11helper.cpp:131: error: ‘KGlobal’ has not been declared", you might need to install libxklavier development packages.<br />
* If you get "/home/kde-devel/kde/lib/libkio.so: undefined reference to `Strigi::AnalysisResult::AnalysisResult(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, long, Strigi::IndexWriter&, Strigi::StreamAnalyzer&)'" you probably have an outdated version of strigi installed by your distro.<br />
<br />
== Running KDE 4 programs ==<br />
<br />
You can now run KDE 4 programs (e.g. kwrite) by typing:<br />
ssh -X kde-devel@localhost<br />
kwrite <br />
<br />
=== Troubleshooting ===<br />
<br />
* If you get <br />
KUniqueApplication: Cannot find the D-Bus session server<br />
check if you can access the display, e.g. type<br />
xclock<br />
and see if a clock appears on the screen.<br />
<br />
* If you get something like<br />
Error: standard icon theme "oxygen" not found!<br />
<br />
ASSERT: "!isEmpty()" in file /home/kde-devel/qt-copy/include/QtCore/../../src/corelib/tools/qlist.h, line 245<br />
Aborted (core dumped)<br />
You need to install kdebase - see above. It is enough to install the "runtime" directory from kdebase.<br />
<br />
== Generating local API documentation ==<br />
Although the API documentation for KDE is available online at [http://api.kde.org api.kde.org], it is sometimes useful to have it on your own disk, for example when you want to use [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|KDevelop]] for browsing the documentation or when you are not able to be online all the time.<br />
<br />
Be aware that generating the API documentation can take several hours and takes almost half a gigabyte of diskspace.<br />
The generation is handled by a script in {{path|kdelibs/doc/api}}, you need <tt>doxygen</tt> to be able to run it. <br />
<br />
To build the API documentation for kdelibs, type the following:<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE/kdelibs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Repeat for other modules as desired.<br><br />
cd <module home><br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Another, even easier method involves downloading this [[Doxyfile]] to your local system. Then simply change directory to where you want to create the documentation and run<br />
<code bash><br />
% doxygen /path/to/Doxyfile<br />
</code><br />
Then review the file {{path|doxygen.log}} to see the doxygen errors and warnings. You'll find the actual documentation in the {{path|apidocs}} subdirectory.<br />
<br />
== Staying up to date ==<br />
<br />
In order to keep the kde4 installation up to date, each of the modules installed should be updated periodically. As Monday is the day for big changes in kdelibs, Tuesday may be the best day to do this. For each module checked out, run <tt>svn up</tt> and <tt>make</tt>.<br />
<br />
For example:<br />
<code bash><br />
cs kdesupport # cs is not a typo<br />
svn up<br />
cb # cb is not a typo<br />
make -j2 VERBOSE=1 && make install<br />
</code><br />
<br />
Note: it is not necessary to run cmakekde for updates.<br />
<br />
== Installing a subset of a module ==<br />
<br />
Many modules in KDE contain a large number of programs which could take a long time to download and compile. In cases where you want to work only on a particular program or programs in a module, it is possible to download and compile particular folders. In some cases, certain folders are required for any build of the module. This is determined in the CMakeLists.txt file of the module. For example the [http://websvn.kde.org/trunk/KDE/kdegames/CMakeLists.txt?view=markup kdegames CMakeLists.txt file] lists:<br />
<br />
<code><br />
add_subdirectory(libkdegames)<br />
add_subdirectory(libkmahjongg)<br />
<br />
macro_optional_add_subdirectory(doc)<br />
macro_optional_add_subdirectory(lskat)<br />
macro_optional_add_subdirectory(katomic)<br />
</code><br />
<br />
So, the libkdegames and libkmahjongg directories are required to build any of kdegames. The cmake directory will also usually be required. All the other directories (doc, katomic etc) are optional. They will be built if present on your machine. In this example, we build kmahjongg and kbattleship:<br />
<br />
<code bash><br />
cs KDE<br />
svn co -N kdegames # The -N switch performs a non-recursive checkout<br />
cd kdegames<br />
svn up libkdegames # Get required directories<br />
svn up libkmahjongg<br />
svn up cmake<br />
svn up kbattleship # Get optional directories<br />
svn up kmahjongg<br />
cmakekde <br />
</code><br />
<br />
== General troubleshooting ==<br />
<br />
What can happen over time, after some <tt>svn up</tt> commands, is that some of the tools used in the KDE build chain change their output format. For example, <tt>kcfg</tt> files are read by <tt>kconfig_compiler</tt> to produce configuration dialogs. CMake cannot detect those changes, and the compilation might fail. A workaround is to always force a re-generation of all such files:<br />
find $KDE_SRC/KDE/kdebase -name "*.kcfg" | xargs touch<br />
The same applies to <tt>ui</tt> files as produced by Qt designer.<br />
<br />
=== Locked sessions ===<br />
When installing KDE 4 as a user, one will not be able to unlock a locked session. To work around this issue you can either:<br />
su<br />
chown root.root $KDEDIR/lib/kde4/libexec/kcheckpass<br />
or<br />
chmod 755 $KDEDIR/lib/kde4/libexec/kcheckpass<br />
<br />
== Success! ==<br />
<br />
You are now ready to start building other svn modules in the same fashion as you built kdebase, running and testing KDE4 or writing your own patches and applications.<br />
<br />
See the [[Getting Started/Set up KDE 4 for development|Set up KDE 4 for development]] tutorial for how to start KDE 4 applications and how to use KDevelop to work on them.<br />
<br />
[[Category:Build KDE]]<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=18742Development/Tutorials/Using KActions (ru)2007-12-26T17:22:30Z<p>Powerfox: Half update (--> XMLGUI section).</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XMLGUI|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]|<br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Действия -- центральная концепция при реализации интерактивности программы.<br />
<br />
Например, если нужно, чтобы пользователь приложения [[Development/Tutorials/Using_KXmlGuiWindow| с урока 2 ]] мог очищать текстовое поле нажатием кнопки на панели инстрментов, комбинацией клавиш или выбрав некоторый пункт меню, то всё это можно реализовать с помощью одного класса {{class|KAction}}.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
== Листинг кода ==<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 />
This time, very little has changed in <tt>main.cpp</tt>, only the KAboutData constructor has been updated to show that we are now on 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 />
Only a function <tt>void setupActions()</tt> has been added which will do all the work setting up the KActions.<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 />
<br />
==Объяснение==<br />
Приложение основано на исходном коде, приведённом в [[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Уроке 2]]. Большинство изменений касаются <tt>mainwindow.cpp</tt>. Конструктор MainWindow теперь вместо <tt>setupGUI()</tt> вызывает <tt>setupActions()</tt>. KAction создаётся и настраивается в функции <tt>setupActions()</tt> до вызова <tt>setupGUI()</tt>.<br />
<br />
<br />
<br />
Для создания действия в <tt>.cpp</tt> необходимо наличие <tt>#include <KAction></tt><br />
=====Создание объекта KAction=====<br />
Мы создадим действие, которое очищающает текстовое поле [[Development/Tutorials/Using_KXmlGuiWindow_(ru)|(см. Урок 2)]]. KAction создаётся в несколько шагов. Первый - включение заголовочного файла и создание объекта KAction:<br />
<code cppqt><br />
#include <KAction><br />
...<br />
KAction* clearAction = new KAction(this);<br />
</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
===Настройка свойств KAction===<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком <tt>KAction</tt> на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста (более подробную информацию можно получить в [[Development/Tutorials/Localization/i18n|уроке по i18n]]<br />
<br />
<br />
=====Значок=====<br />
В случае отображения действия на панели неплохо использовать значок, характеризующий это действие. Следующий код с помощью функции <tt>setIcon()</tt> устанавливает стандартный значок KDE <tt>document-new</tt><br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
<br />
=====Комбинация клавиш=====<br />
Связать комбинацию клавиш с нашим действием совершенно просто:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code><br />
Данный фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XMLGUI (более подробное объяснение приведено дальше), следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XMLGUI.<br />
<br />
<br />
=====Соединение действия с обработчиком=====<br />
<br />
Теперь, когда параметры внешнего вида действия определены, можно связать его с методом tt>clear()</tt> объекта KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Интерфейс класса аналогичен {{qt|QAction}}, в KAction лишь добавлены специфические для KDE особенности.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit, save, и load, доступны готовые объекты KAction, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит пункт в меню File.<br />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), следует использовать KDE-технологию XMLGUI. <br />
<br />
{{note|В последующих версиях KDE4, XMLGUI может быть заменена на систему liveui. Но сейчас XMLGUI является единственным правильным способом настройки UI.}}<br />
<br />
<br />
===XMLGUI===<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
<ActionList name="dynamicActionlist" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
Заметьте, что таким же способом можно динамически добавлять список действий, используя тэг <tt><ActionList></tt>. Для получения более подробной информации обратитесь к документации по методу <tt>plugActionList()</tt> класса {{class|KXMLGUIClient}}. <br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы проверить её (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/First_program_(ru)&diff=18156Development/Tutorials/First program (ru)2007-12-15T19:37:04Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/First_program}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Hello World|<br />
<br />
pre=[http://mindview.net/Books/TICPP/ThinkingInCPP2e.html C++], [http://www.trolltech.com/products/qt/ Qt], [[Getting_Started/Build/KDE4_(ru)|Сборка и настройка KDE4]]|<br />
<br />
next=[[Development/Tutorials/Using_KXmlGuiWindow_%28ru%29|Урок 2 - KXmlGuiWindow]]| <br />
<br />
reading=[[Development/Tutorials/CMake|CMake]]<br />
}}<br />
<br />
==Введение==<br />
Первая программа приветствует мир дружелюбным "Hello World". Для этого будет использован {{class|KMessageBox}} с изменением одной из кнопок.<br />
[[image:introtokdetutorial1.png|frame|center]]<br />
<br />
{{tip|Для получения большей информации о каком-либо классе, с которым вы работаете, Konqueror предоставляет возможность быстрого вызова справки. Таким образом, чтобы посмотреть информацию о KMessageBox, просто введите "kde:kmessagebox" в Konqueror, и будет открыта документация.}}<br />
<br />
{{tip|<br />
Для работы с проектами можно использовать KDevelop, имеющий такие функции, как дополнение кода, лёгкий доступ к документации по API или поддержка отладки, удобство которых вы обязательно оцените после получения минимального опыта программирования.<br />
<br />
В [[Getting_Started/Set_up_KDE_4_for_development_(ru)#KDevelop|этом документе]] описывается настройка KDevelop для данной задачи. Проверить, работают ли настройки, можно попробовав открыть проект существующего приложения KDE4 с помощью KDevelop.<br />
<br />
Тем не менее, файлы CMake по-прежнему нужно редактировать вручную.<br />
}}<br />
<br />
==Код==<br />
Весь необходимый код находится в <tt>main.cpp</tt>. Создайте файл с кодом, приведённым ниже:<br />
<code cppqt><br />
#include <QString><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KMessageBox><br />
#include <KCmdLineArgs><br />
#include <KLocalizedString><br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData("tutorial1", // Имя программы используется для внутренних нужд.<br />
0, // Имя директории с сообщением (The message catalog name), используется имя программы, если 0.<br />
ki18n("Tutorial 1"), // Отображаемое имя программы.<br />
"1.0", // Строка с информацией о версии программы.<br />
ki18n("KMessageBox popup"), // Краткое описание того, что делает программа.<br />
KAboutData::License_GPL, // Тип лицензии.<br />
ki18n("(c) 2007"), // Заявление об авторском праве.<br />
ki18n("Some text..."), // Произвольный текст, содержащий информацию любого рода.<br />
"http://tutorial.com", // Адрес домашней страницы программы<br />
"submit@bugs.kde.org"); // Строка с адресом электронной почты для сообщений об ошибках.<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 />
<br />
Первый KDE код, который был встречен в программе - {{class|KAboutData}}. Это специальный класс для хранения такой информации о программе, как краткое описание, авторы, тип лицензии. Почти каждое (Pretty much) KDE-приложение должно использовать этот класс.<br />
<br />
Затем был использован {{class|KCmdLineArgs}}. Этот класс позволяет задать параметры командной строки, например, чтобы запускать программу с заданным файлом. Однако, в этом туториале мы просто инициализировали этот класс с помощью созданного объекта {{class|KAboutData}}. Так что можно использовать параметры командной строки <tt>--version</tt> or <tt>--author</tt>.<br />
<br />
В строке 13 был создан объект {{class|KApplication}}. Он нужен для таких вещей, как [[Development/Tutorials/Localization/i18n|поддержка перевода программ на другие языки]].<br />
<br />
Теперь, когда все требуемые начальные действия относящиеся к KDE выполнены, можно перейти к созданию интересных вещей для нашего приложения. Мы собираемся сделать всплывающее окно (popup box), кроме того, мы изменим одну из кнопок. Чтобы это сделать, нужен объект {{class|KGuiItem}}. Первый аргумент в конструкторе {{class|KGuiItem}} - текст, который отображается на элементе (в нашем случае - кнопке). Следующий параметр - значок для кнопки, но нам это не нужно, поэтому мы опускаем его, написав <tt>QString()</tt>. Наконец, мы задаём текст всплывающей подсказки (который появляется при наведении курсора на элемент) и текст для "What's This(Что это такое)?" (доступно через правый щелчок мышью или же Shift-F1)<br />
<br />
Теперь элемент настроен, и мы можем создать всплывающее окно (popup). Для этого вызывается функция <tt>KMessageBox::questionYesNo()</tt>, которая по умолчанию создаёт MessageBox с кнопками "Да", "Нет". Второй аргумент - текст, который будет выведен посередине диалогового окна.<br />
Третий - заголовок, который будет задан для окна и, наконец, мы используем KGuiItem (что будет нормально работать) для кнопки "Да" в <tt>KGuiItem guiItem</tt>, который нами создан.<br />
<br />
Теперь, когда мы закончили ознакомление с кодом, время собрать и запустить наше приложение.<br />
<br />
==Сборка==<br />
Если системное окружение было настроена так, как описано в [[Getting Started/Build/KDE4_(ru)]], то код можно скомпилировать так:<br />
<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 />
А затем запустить с помощью <br />
dbus-launch ./tutorial1<br />
<br />
===Использование CMake===<br />
Процесс сборки автоматизируется с помощью [[Development/Tutorials/CMake|CMake]]. Он самостоятельно определяет расположение библиотек и заголовочных файлов KDE, Qt и др. Использование CMake упрощает сборку приложения на другом компьютере.<br />
<br />
====CMakeLists.txt====<br />
Создайте файл с именем CMakeLists.txt со следующим содержанием в той же директории, что и main.cpp <br />
<code><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 />
<br />
Функция <tt>find_package()</tt> находит заданный пакет (в данном случае KDE4) и устанавливает определённые переменные, описывающие расположение заголовков и библиотек пакета. В данном примере использована переменная <tt>KDE4_INCLUDES</tt>, которая содержит путь к заголовочным файлам KDE4.<br />
<br />
Чтобы компилятор нашёл эти файлы, нужно передать эту переменную функции <tt>include_directories()</tt>, которая добавит директорию с заголовками KDE4 в поиск (search path).<br />
<br />
Далее была создана переменная <tt>tutorial1_SRCS</tt>, инициализированная с помощью функции <tt>set()</tt>. В данном случае, ей было просто задано имя исходного файла.<br />
<br />
Затем была использована функция <tt>kde4_add_executable()</tt>, чтобы создать исполняемый файл <tt>tutorial1</tt> из исходных файлов, перечисленных в переменной <tt>tutorial1_SRCS</tt>. Наконец, указывается библиотека KDE4 kdeui для линковки с файлом с помощью <tt>target_link_libraries()</tt> и переменной <tt>KDE4_KDEUI_LIBS</tt>, заданной с помощью функции <tt>find_package()</tt>.<br />
<br />
====Выполнение сборки и запуск (Make and Run)====<br />
Опять же, если системное окружение было установлено так, как описано в [[Getting Started/Build/KDE4]], данный исходный код можно скомпилировать с помощью<br />
cmakekde<br />
<br />
Если нет, то:<br />
<br />
mkdir build<br />
cmake .. && make<br />
<br />
И запустить<br />
./tutorial1.shell<br />
<br />
==Продолжим изучение==<br />
Теперь можно перейти к [[Development/Tutorials/Using_KXmlGuiWindow_(ru)|статье о KXmlGuiWindow]].<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4&diff=14134Getting Started/Build/KDE42007-09-26T18:16:49Z<p>Powerfox: /* The Recipe */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Getting Started|<br />
<br />
name=Building KDE4 From Source|<br />
<br />
pre=[[../../Sources/Anonymous_SVN|Anonymous SVN Quickstart Guide]]|<br />
<br />
next=[[../../Set_up_KDE_4_for_development|Set up KDE 4 for development]]|<br />
<br />
reading=[http://kdesvn-build.kde.org/ kdesvn-build: The KDE From Subversion Build Tool]<br>[[../../Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br>[[Development/Tutorials/CMake |Introduction to CMake]]<br>[[../KDE4/FreeBSD|FreeBSD notes]]<br>[[../KDE4/Mac OS X|Instructions for Mac OS X]]<br>[[../KDE4/Windows|Instructions for MS Windows]]|<br />
}}<br />
<br />
== Abstract ==<br />
<br />
This tutorial shows one way to get KDE from trunk running on Linux/BSD systems. There are also tutorials for [[/FreeBSD|FreeBSD]], [http://www.kdelibs.com/ Windows], [[/Mac OS X|Mac OS X]] and [http://solaris.kde.org/ Solaris]. Throughout the tutorial the bash shell is used.<br />
<br />
{{warning|Expect a higher risk of build failure '''on Mondays''' when most kdelibs changes are committed. [http://developer.kde.org/~dirk/dashboard/ Dashboard] reports unexpected breakages. You are encouraged to fix failing modules.<br />
}}<br />
<br />
== Required Software ==<br />
<br />
The following must be installed first before you can successfully complete this tutorial:<br />
* gcc and g++, preferably version 4.1 or higher<br />
* svn, the subversion revision control client<br />
* pkg-config<br />
* development libraries and headers for X11, OpenGL (mesa-common-dev and libglu1-mesa-dev), libjpeg, libpng, libungif, [http://clucene.sourceforge.net/index.php/Downloads libclucene], [http://download.librdf.org/source/ librdf], libxml2 and libxslt<br />
* the <tt>makeobj</tt> script, which is part of kdesdk. You can install it as part of kdesdk (kdesdk-scripts on Debian) or similar package, or just download it itself from [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/makeobj WebSVN]<br />
* the [http://freedesktop.org/wiki/Software/shared-mime-info shared-mime-info package], which is the freedesktop MIME standard KDE is using now<br />
* [http://boost.org/ boost], needed by kdebase; after compiling and/or installing boost, in order to make cmake aware about its location (FindBoost), add boost directory (the one containing include subdirectory) to CMAKE_INCLUDE_PATH or set an environment variable called BOOST_ROOT pointing to boost directory.<br />
<br />
=== Ark Linux ===<br />
In Ark Linux, the build dependencies you need are installed with:<br />
<br />
<code bash><br />
apt-get install devel-core libxml-devel libxslt-devel bzip2-devel \<br />
clucene-core-devel librdf-devel shared-mime-info xorg-Mesa-libGL-devel \<br />
subversion boost-devel doxygen giflib-devel dbus-devel openssl-devel \<br />
alsa-lib-devel kdesdk-scripts qt4-devel<br />
</code><br />
<br />
If you prefer a graphical interface, select the packages listed above in the "Install Software" tool in Mission Control.<br />
<br />
This includes installation of CMake, DBus and Qt - you can skip steps 5, 6 and 7.<br />
<br />
=== Kubuntu and Debian ===<br />
<br />
In Kubuntu 7.04 (Feisty) and Debian (Testing/Unstable) the build dependencies you need are installed with:<br />
<code bash><br />
sudo aptitude install build-essential cdbs debhelper cmake \<br />
libxml2-dev libxslt1-dev libbz2-dev libclucene-dev librdf-dev \<br />
shared-mime-info libgl1-mesa-dev libglu1-mesa-dev mesa-common-dev \<br />
libxext-dev libjpeg-dev libpng-dev subversion libsm-dev libxinerama-dev \<br />
libxrender-dev libfontconfig-dev libboost-dev libxcursor-dev doxygen \<br />
libungif4-dev libdbus-1-dev libgpgme11-dev libssl-dev libgpgme11-dev \<br />
libasound2-dev kdesdk-scripts libpth-dev libjasper-dev ssh<br />
</code><br />
<br />
In Kubuntu 7.10 (Gutsy) you have to add:<br />
<code bash><br />
sudo aptitude install dbus-x11<br />
</code><br />
<br />
For a fully functional API documentation framework you also need:<br />
<code bash><br />
sudo aptitude install graphviz<br />
</code><br />
<br />
=== openSUSE ===<br />
<br />
In openSUSE 10.2 and newer, you can install packages using [http://en.opensuse.org/Zypper Zypper]:<br />
<code bash><br />
sudo zypper install <package-name><br />
</code><br />
<br />
In older releases of SUSE, you can use YaST:<br />
<code bash><br />
su<br />
yast -i <packagename><br />
</code><br />
<br />
'''Required Packages'''<br />
<br />
The packages you will need to install are:<br />
<code><br />
xorg-x11-devel<br />
libxml2-devel <br />
kdesdk3 <br />
clucene-core-devel <br />
boost-devel<br />
libjpeg-devel <br />
liblrdf-devel <br />
libpng-devel <br />
libxslt-devel <br />
libredland-devel<br />
Mesa-devel <br />
giflib-devel <br />
subversion <br />
gcc <br />
gcc-c++<br />
gmp-devel (needed to build kdesupport)<br />
strigi-devel (needed to build kdelibs)<br />
gpgme-devel (needed to build kdepimlibs)<br />
</code><br />
<br />
'''Optional Packages'''<br />
<br />
You can skip the manual installation of Qt 4.3, CMake 2.4.6 and DBus by installing the adding the openSUSE Build Service KDE4 Repository to your installation sources.<br />
<br />
For openSUSE 10.2 and newer do:<br />
<code><br />
sudo zypper service-add http://software.opensuse.org/download/KDE:/KDE4/openSUSE_10.2 KDE4-102<br />
</code><br />
<br />
For older versions of SUSE Linux do:<br />
<code><br />
su<br />
installation_sources -a http://software.opensuse.org/download/KDE:/KDE4/[YOUR SUSE LINUX VERSION]<br />
</code><br />
<br />
Now install the following packages (and their dependencies):<br />
<code><br />
cmake<br />
dbus-1-devel<br />
libqt4-devel<br />
libqca2-devel (needed for building kdesupport)<br />
</code><br />
<br />
And for fully functional apidox framework you also need:<br />
<code><br />
graphviz<br />
</code><br />
<br />
CMake binary packages for openSUSE are available from [http://software.opensuse.org/download/devel:/tools:/building/ openSUSE build service].<br />
<br />
=== Gentoo ===<br />
<br />
==== Install by hand ====<br />
<br />
You can use stable ebuilds just remember to sync your portage before you begin.<br />
<br />
Remember: All commands are executed as root.<br />
<br />
Required:<br />
<br />
We need to allow the following keyword masked ebuilds.<br />
<br />
<code bash><br />
echo 'dev-util/cmake' >> /etc/portage/package.keywords<br />
echo 'dev-cpp/clucene' >> /etc/portage/package.keywords<br />
</code><br />
<br />
Optional:<br />
<br />
If you decide not to use the KDE qt-copy, you need to keyword unmask Qt.<br />
<br />
<code bash><br />
echo 'x11-libs/qt' >> /etc/portage/package.keywords<br />
</code><br />
<br />
And now need to mask any Clucene versions above 0.9.16a.<br />
<br />
<code bash><br />
echo '>dev-cpp/clucene-0.9.16a' >> /etc/portage/package.mask<br />
</code><br />
<br />
Make sure you have set the berkdb USE flag for redland, otherwise nepomuk won't work.<br />
<br />
<code bash><br />
echo 'dev-libs/redland berkdb' >> /etc/portage/package.use<br />
</code><br />
<br />
These are the packages you will need to emerge, I included the update option into the emerge command so you will not re-emerge anything that you might already have installed.<br />
<br />
<code bash><br />
emerge -avu 'sys-devel/gcc' \<br />
'dev-util/subversion' \<br />
'dev-util/pkgconfig' \<br />
'x11-base/xorg-x11' \<br />
'virtual/glut' \<br />
'media-libs/mesa' \<br />
'media-libs/jpeg' \<br />
'media-libs/libpng' \<br />
'media-libs/giflib' \<br />
'dev-cpp/clucene' \<br />
'dev-util/cppunit' \<br />
'media-libs/liblrdf' \<br />
'dev-libs/libxml2' \<br />
'dev-libs/libxslt' \<br />
'x11-misc/shared-mime-info' \<br />
'dev-libs/boost' \<br />
'dev-util/cmake' \<br />
'dev-libs/redland' \<br />
'sys-apps/dbus' \<br />
'sys-apps/hal'<br />
</code><br />
<br />
You will also need to emerge either 'kde-base/kdesdk' or kde-base/kdesdk-scripts'.<br />
<br />
Optional:<br />
<br />
If you decided to use Gentoo's version of Qt4, you can emerge it using the following command.<br />
<br />
<code bash><br />
emerge -avu 'x11-libs/qt'<br />
</code><br />
<br />
<br />
If you emerged DBUS, CMAKE, QT or HAL you may skip those sections respectively.<br />
Good luck!<br />
<br />
==== Install via portage ====<br />
<br />
Also you can install the KDE 4 packages directly via <br />
<code bash><br />
emerge -a <packagename><br />
</code><br />
<br />
To get the things you need, [http://gentoo-wiki.com/TIP_Overlays#Layman install layman] and then pull in the KDE overlay (which contains experimental KDE ebuilds): <br />
<code bash><br />
layman -a kde<br />
</code><br />
After this you need to adjust some USE-flags for KDE 4 and tell portage to use the testing KDE 4 ebuilds instead of the stable KDE 3 ones. <br />
<br />
That way portage will do the dependency tracking for you. <br />
<br />
Detailed instructions on building KDE 4 in Gentoo via portage can be found in the [http://overlays.gentoo.org/proj/kde/wiki KDE overlay wiki]. They are discussed in the thread [http://forums.gentoo.org/viewtopic-t-530111-postdays-0-postorder-asc-start-0.html KDE 4 monolithic ebuilds].<br />
<br />
== Create a user account for KDE4 development ==<br />
<br />
{{Note|<br />
Some people like to have a separate user account for KDE 4 (for instance an old bug deleted files by mistake), and the instructions below were written with that approach.<br />
<br />
However it is much more efficient to do everything with a single user account, see [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br />
for more details. <br />
<br />
You can still follow the instructions below, but don't put the environment variables in your <tt>.bashrc</tt>, put them in a separate file that you source to switch to the KDE 4 environment.<br />
}}<br />
<br />
=== Option 1: Command Line ===<br />
<code bash><br />
useradd -m kde-devel<br />
passwd kde-devel<br />
</code><br />
<br />
=== Option 2: Using KControl ===<br />
<br />
Instead of using the commands above, you can also use the User module in the KDE Control Center if you already have KDE3 installed.<br />
<br />
=== Setting up the environment ===<br />
<br />
Copy the {{path|~/.bashrc}} from your normal user account to the new kde-devel account. Next, copy and paste the contents of the [[Getting Started/Increased Productivity in KDE4 with Scripts/.bashrc|example .bashrc]] into {{path|~kde-devel/.bashrc}}. Be sure to comment out the line <tt>alias make=makeobj</tt> if you do not have the <tt>[[Getting Started/Build/KDE4#Required Software|makeobj]]</tt> command available. You will probably also want to modify the path to make sure it doesn't include your kde3 paths. Also if you want to use KDevelop to develop KDE 4 applications you may pass the ''-GKDevelop3'' flag to the ''cmake'' command (to make CMake generate KDevelop project files, it will help to avoid rebuilding in the future, see [[Getting_Started/Set_up_KDE_4_for_development#Setting_up_the_environment|this]]). <br />
To make it run, you have to open a new bash or to execute <br />
<code bash><br />
source ~/.bashrc<br />
</code><br />
<br />
This will provide access to commands such as <tt>cmakekde</tt> that are used in this tutorial as well as ensure that the proper paths are in place for Qt, KDE and CMake binaries.<br />
<br />
For more information, please read the [[Getting Started/Increased Productivity in KDE4 with Scripts]] tutorial.<br />
<br />
=== Switching to the New User ===<br />
Switch to the user kde-devel: (don't forget the dash)<br />
<code bash><br />
ssh -X kde-devel@localhost<br />
</code><br />
<br />
== The development user's shell ==<br />
<br />
On some systems a new user is configured by default to use {{path|/bin/sh}}. If this is not the case on your system, you can skip this section. Using {{path|/bin/sh}} can be very inconvenient to work with and you may want to change it to {{path|/bin/bash}} or another shell.<br />
On Ark Linux, you can skip this step - {{path|/bin/sh}} is {{path|bash}} on Ark Linux.<br />
<br />
=== Option 1: As the kde-devel user ===<br />
<br />
If you don't have root privileges and your system supports the changing of your own shell with the <tt>chsh</tt> application, then you could try to change your shell to {{path|/bin/bash}} by using:<br />
<code bash><br />
chsh -s /bin/bash kde-devel<br />
</code><br />
<br />
=== Option 2: As the root user ===<br />
<br />
If your system comes with the <tt>usermod</tt> application you can run the following command as root: <tt>usermod -s /bin/bash</tt>.<br />
<br />
Another option is to use the <tt>vipw</tt> application as root to safely edit your {{path|/etc/passwd}}. Locate 'kde-devel' in the the file. Change '{{path|/bin/sh}}' at the end of the line to read '{{path|/bin/bash}}', save your changes and exit.<br />
<br />
The new shell will be started automatically when you log in as the kde-devel user again.<br />
<br />
== D-Bus ==<br />
QtDBus and KDE are known to work with D-Bus versions 0.62, as well as 0.92 and upwards. Versions 0.60 and 0.61 may work too but are not tested. Versions 0.90 and 0.91 are known not to work. We recommend using post-1.0 release versions (at least 0.94), so consider upgrading if you haven't done so.<br />
<br />
You may skip this section if you have a recent D-Bus version or if you don't want to upgrade. You probably want to skip building the bindings until/unless you know you will be building HAL (see below).<br />
<br />
Before running these steps in the recipe, make sure your X11 headers and libraries are available. The configure script run on line 5 of the following instructions should output:<br />
Building X11 code: yes<br />
<br />
=== The Recipe ===<br />
<br />
{{tip|Make sure you did set up your environment correctly as described [[Getting_Started/Build/KDE4#Setting_up_the_environment|above]]. This is necessary for the <tt>cs</tt> and <tt>cb</tt> functions to work.}}<br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]] <br />
wget http://dbus.freedesktop.org/releases/dbus/dbus-1.0.2.tar.gz<br />
tar -xvzf dbus-1.0.2.tar.gz<br />
cd dbus-1.0.2/<br />
./configure --prefix=$DBUSDIR --localstatedir=/var<br />
make<br />
sudo make install<br />
sudo dbus-uuidgen --ensure<br />
<br />
cs # see above<br />
wget http://dbus.freedesktop.org/releases/dbus-glib/dbus-glib-0.74.tar.gz<br />
tar -xvzf dbus-glib-0.74.tar.gz<br />
cd dbus-glib-0.74/<br />
./configure --prefix=$DBUSDIR<br />
make<br />
sudo make install<br />
<br />
=== What's Happening === <br />
After changing into the source directory (line 1), D-Bus source code is downloaded from freedesktop.org (line 2) and unpacked (line 3). After going into the newly created D-Bus directory (line 4), the build is set up using the supplied {{path|configure}} script (line 5). After building (line 6) and installing (line 7) D-Bus, we use the <tt>dbus-uuidgen</tt> tool to install a machine identification file that allows the bus to start automatically when the desktop session starts (line 8).<br />
<br />
Note that you need write access to {{path|/var}} for the last two steps. If your system does not have the sudo command, you can use the <tt>su</tt> command instead, e.g. <tt>su -c "make install"</tt>.<br />
<br />
The steps for building the glib bindings are similar to the above.<br />
<br />
== CMake ==<br />
Skip this if you have [http://cmake.org/ CMake] >=2.4.5 installed. <br />
You should be able to directly use the binary packages available on the [http://www.cmake.org/HTML/Download.html CMake site]. There are also distribution specific packages available.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click Here to learn more]] <br />
wget http://www.cmake.org/files/v2.4/cmake-2.4.6.tar.gz<br />
tar -zxf cmake-2.4.6.tar.gz<br />
mkdir cmake-build<br />
cd cmake-build <br />
../cmake-2.4.6/bootstrap<br />
make<br />
sudo make install<br />
<br />
=== What's Happening ===<br />
First, we go back to the <tt>kde-devel</tt> user's source directory (line 1), get the CMake sources (line 2) and unpack them (line 3). We create a directory to build CMake in (line 4) and go into it (line 5). We then run the CMake bootstrap script to set up the CMake build (line 6), then make (line 7) and install it (line 8) using the root user.<br />
<br />
If your system does not have the <tt>sudo</tt> command, you can instead do <tt>su -c "make install"</tt>.<br />
<br />
== Qt ==<br />
Next we need to get the Qt4 that is in KDE's source repository. KDE is guaranteed to build against any Qt 4.3. Qt 4.2 and earlier are not supported and will not work. You should use the copy in the KDE Subversion servers. (note: some distros, like Debian, tend to supply Qt with patches from KDE svn applied, so you may want to cheat and use precompiled Qt from your distro)<br />
<br />
=== The Recipe ===<br />
cs<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/qt-copy<br />
cd qt-copy<br />
./apply_patches<br />
./configure -qt-gif -no-exceptions -debug -fast \<br />
-prefix $QTDIR -nomake examples -nomake demos<br />
make -j2<br />
<br />
# if we don't install, we'll just clear obj files to<br />
# save disk space<br />
if [ $QTDIR = `pwd` ]; then \<br />
find . -name '*.o' -delete ; \<br />
else make install; fi;<br />
<br />
=== What's Happening ===<br />
We switch back to the <tt>kde-devel</tt> user's home directory (line 1) and download the source code using subversion (svn) from KDE's repository (line 2). After changing into the resulting {{path|qt-copy}} directory (line 3), we run a script that manages the patches that come with <tt>qt-copy</tt> (line 4). <br />
<br />
Once the patches have been applied, we then set up the build using the <tt>configure</tt> script (line 5-6). The various command line options used are explained in the {{path|qt-copy/README.qt-copy}} file. Finally, we build the minimal requirements for KDE (line 7) and install (line 10) Qt. If install dir is the same as the current dir (line 8), then we just free some space (line 9) instead. If you want all the example and demo applications, you can either build them individually or simply do a <tt>make</tt> from the {{path|qt-copy}} directory. <br />
<br />
Note that the installation does not require root as it installs Qt locally into {{path|$QTDIR}}. Anyway, installation is only needed if {{path|$QTDIR}} differs from {{path|$HOME/qt-copy}}, which is not the case if you have exactly followed the instructions.<br />
<br />
=== Troubleshooting ===<br />
If you get "error: X11/Xlib.h: No such file or directory", install the devel package of <tt>xorg</tt> (the actual name may vary between operating systems, for example it is <tt>xorg-dev</tt> on Ubuntu based systems such as Kubuntu). <br />
<br />
If you get an error in the configure step about missing defines, check the value of <tt>$QMAKESPEC</tt>. Some distributions set this to point directly to the system-installed Qt. If <tt>unset QMAKESPEC</tt> solves the problem, you probably want to add it to the <tt>~/.bashrc</tt> script.<br />
<br />
If you get an error ".pch/debug-shared/QtCore", this is because Qt-4.3 enables precompiled headers if your gcc supports it, but for some reason it doesn't work for you. If you use distcc, configure qt with -no-pch. If you use icecream, update to the latest icecream from svn trunk.<br />
<br />
Try running any Qt program, like {{program|assistant}}. '''Note:''' You may need to run <tt>xhost +local:kde-devel</tt> as your regular kde3 user to run this application. If it crashes in QSpanData::adjustSpanMethods, then your problem is the oxygen style. Try removing {{path|lib/kde4/plugins/styles/kstyle-oxygen.so}} and {{path|lib/kde4/plugins/styles/oxygen.so}} if they exist in the KDE install prefix.<br />
<br />
== HAL ==<br />
<br />
{{tip|You can use qdbusviewer to see if you have org.freedesktop.hal. If not, you might need a newer version of hal. If you have org.freedesktop.hal, you probably don't need to, and don't ''want'' to, roll your own HAL.}}<br />
<br />
If your system requires you to build a newer version of HAL, there's a decent chance you'll need to build other stuff as well, some of which may not be straight forward. Since this should only be required for older distros, instructions are on [[Getting_Started/Build/HAL| a separate page]].<br />
<br />
== kdesupport ==<br />
<br />
{{warning|Don't forget to read the [[Getting_Started/Build/KDE4#Setting_up_the_environment|Setting Up The Environment]] section first.}}<br />
<br />
There are several libraries that KDE applications rely on in the kdesupport module. This includes Strigi and Soprano for file metadata and search, QImageBlitz for image manipulation needed in kdebase, eigen for visual effects in applications such as Kalzium, taglib for music players and qca for some cryptographic needs. <br />
<br />
Strigi itself has a few dependencies as well: you will need the libraries and headers for libz, libbz2, openssl (libcrypto or libssl), libclucene (=0.9.16; version 0.9.17 does '''not''' work), and either libxml2 or libexpat.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/kdesupport/<br />
cd kdesupport<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1). We download the sources in kdesupport using subversion (line 2), go into the new {{path|~/kde/src/kdesupport}} directory (line 3), and commence the build (line 4). This will leave us in the kdesupport build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you get <br />
cmakekde: command not found<br />
then you have to go manualy into the kdesupport directory in ~ and execute the command cmakekde. if this still doesnt work, then something is wrong with your bashrc.<br />
<br />
If you get <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 />
LIBXML2_INCLUDE_DIR (ADVANCED)<br />
you should install the development package for libxml2.<br />
<br />
If you get <br />
CMake Error: Could NOT find REDLAND<br />
then you need librdf from the Redland.<br />
If your distribution does not provide the librdf package, you can download the source there: [http://download.librdf.org/source/ http://download.librdf.org/source/] and build it.<br />
(Gentoo users: The ebuild for librdf is named dev-libs/redland)<br />
<br />
If you get<br />
Fetching external item into 'kdesupport/admin'<br />
Error validating server certificate for 'https://...'<br />
see [http://techbase.kde.org/Getting_Started/Sources/Using_Subversion_with_KDE Using Subversion with KDE]<br />
<br />
If you get<br />
FILE cannot create directory: /usr/lib[64]/qt4/plugins/crypto. Maybe need administrative privileges.<br />
- - -<br />
make: *** [install] Error 255<br />
take a second look in the .bashrc file described above, are paths correct? Alternatively, you may see this error if you decided to use a distribution installed version of qt4 and skipped the Qt install above. Either install qt-copy as describe above, or "sudo make install". If you use "sudo make install", make sure you that you change the ownership back to your user for some of the ~/kde subdirectories that were effected by using sudo (ie. "<tt>sudo chown -R kde-devel:kde-devel ~/kde</tt>").<br />
<br />
== kdelibs ==<br />
<br />
We can now move on to building KDE's base libraries.<br />
<br />
=== The Recipe ===<br />
cd <br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
mkdir KDE && cd KDE<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdelibs<br />
cd kdelibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1) then make and go into the KDE directory (line 2). We download the sources for kdelibs using subversion (line 3), go into the new {{path|~/kde/src/KDE/kdelibs}} directory (line 4), and commence the build (line 5). This will leave us in the <tt>kdelibs</tt> build directory after the build is completed.<br />
<br />
{{tip|There might be missing dependencies on your system! They are easily overlooked in the output of <tt>cmakekde</tt>.<br />
You might want to do a <tt>cmake $KDE_SRC/KDE/MODULE_NAME</tt> prior to compiling any kde modules (like kdelibs, kdepimlibs etc.)}}<br />
<br />
=== Additional KDE-specific CMake modules ===<br />
There are additional CMake modules in {{path|kdelibs/cmake/modules/}} that are necessary for building KDE4 applications. These will be installed for you when kdelibs itself is installed.<br />
<br />
=== Troubleshooting ===<br />
If you have problems compiling kdelibs, first make sure the software in the [[Getting_Started/Build/KDE4#Required_Software|Required Software]] section above is installed and works. Other possible hints include:<br />
* If the <tt>cmakekde</tt> command fails stating that CMake requires an out of source build directory, remove {{path|~/kde/src/KDE/kdelibs/CMakeCache.txt}}, and try again.<br />
<br />
If <tt>cmakekde</tt> still gives the same error then try this <br />
cd<br />
cmake -DCMAKE_INSTALL_PREFIX=$KDEDIR \<br />
-DCMAKE_BUILD_TYPE=debugfull \<br />
-DKDE4_BUILD_TESTS=ON \<br />
~/kde/src/KDE/kdelibs<br />
make<br />
make install<br />
* If you received an error stating "Please create a separate build directory and run 'cmake path_to_kdelibs [options]' there.", then you need to change to your build directory before running cmakekde. (e.g <tt>cs KDE/kdelibs && cb && cmakekde</tt>) If the message stays, run 'svn status' in the kdelibs directory and remove all files labeled with '?'.<br />
* If Qt wasn't found or the wrong version of Qt was found, make sure that the qmake from the Qt you need is the first qmake in the path.<br />
* If the problems persist, try the CMake make-option <tt>--keep-going</tt>.<br />
* Here you need the libungif library, otherwise you will get an error message like "<tt>Could NOT find GIF</tt>".<br />
* Qt-4.3 upgrade: if you get a link error in kjsembed talking about QScriptEngine, edit CMakeCache.txt in kdelibs and remove the lines that talk about QT_QTUITOOLS_LIBRARY, then type make again (that static library has a new dependency, and the cmake code that adds it needs to run).<br />
* if you get <code>CMake Error: KDE Requires Qt to be built with SSL support<br />
</code>, install openssl-devel, remove CMakeCache.txt and re-compile QT.<br />
* if you get <code>kdelibs/kimgio/ico.cpp:188: undefined reference to `QImage::jumpTable()'</code> it means you compiled QT without QT3 support(no, linking to a true QT3 install won't work)<br />
<br />
== kdepimlibs ==<br />
After <tt>kdelibs</tt>, but before ''kdebase'', you need to build and install ''kdepimlibs''.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdepimlibs<br />
cd kdepimlibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We go into the KDE source directory (line 1), download the source code for kdepimlibs using subversion (line 2) and then go into the new {{path|~/kde/src/KDE/kdepimlibs}} directory (line 3). We then commence the build (line 4). This will leave us in the <tt>kdepimlibs</tt> build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you have trouble compiling kdepimlibs:<br />
* the cmakekde command may require a later version of the gpgme library. This is available from the project's web site: http://www.gnupg.org/(en)/download/index.html - please note that the build of gpgme also requires libgpg-error, also available from the same location. Both libraries are installed by the "./configure", "make" and "sudo make install" sequence, with the gpgme library configured with the additional "--with-gpg-error-prefix" parameter. You may need to overwrite your existing "/usr/bin/gpgme-config" file with the newer version for the kdepimlibs to pick up the new install.<br />
<br />
== kdebase ==<br />
kdebase is divided into three parts:<br />
* '''apps'''<br />
:This contains applications like Dolphin or KWrite.<br />
* '''runtime'''<br />
:This contains things needed by every application at runtime, like icons. It is a required dependency for each KDE application, so you have to compile and install this.<br />
* '''workspace'''<br />
:This contains things specific to the KDE desktop, like Plasma or the window manager. Most stuff here depends on X11. You only need it if you want to build a full KDE desktop.<br />
<br />
You can build all of kdebase at once, which is described in the recipe below. If you only want to build kdebase-runtime, which is the only requirement, you can replace <code bash>cd kdebase</code> with <code bash>cd kdebase/runtime</code> in the recipe below.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdebase<br />
cd kdebase<br />
cmakekde<br />
<br />
=== Troubleshooting ===<br />
If you have troubles compiling kdebase:<br />
* Make sure you have the <tt>libxss headers</tt> installed. (Usually you got undefined references on xscreensaver objects if you do not have those headers)<br />
* <tt>which meinproc</tt> has to deliver {{path|/home/kde-devel/kde/bin/meinproc}}<br />
* if cmakekde can not find the path of kdepimlibs, edit the file {{path|$KDE_BUILD/KDE/kdebase/CMakeCache.txt}} and manually set <tt>KDEPIMLIBS_INCLUDE_DIR:PATH=$KDE_BUILD/kdepimlibs</tt><br />
* if you get an error saying "Please set the following variables: X11_XTest_LIB (ADVANCED)", install the devel package of <tt>Xtst</tt>. On some systems, this is packaged separately from <tt>xext</tt> and called <tt>x11proto-xext-dev</tt> or <tt>libxtst-dev</tt>. You may also need to remove the CMakeCache.txt file in the build dir after installing the package.<br />
* the same for "X11_Xinerama_LIB (ADVANCED)" where you will need the devel package for <tt>xinerama</tt>.<br />
* if you get an error complaining about a missing variable X11_Xrandr_LIB, you need the devel package for libxrandr (libxrandr-devel on ubuntu-systems)<br />
* if you get the error "Please set the following variables: FONTCONFIG_INCLUDE_DIR, FONTCONFIG_LIBRARIES (ADVANCED)", then you need to install the libfontconfig headers<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: KMETADATA_LIBRARIES", you need to install soprano from kdesupport and to rebuild kdelibs<br />
* if you get the error "‘XserverRegion’ does not name a type" make sure you have libxcomposite headers installed (<tt>libxcomposite-dev</tt> in ubuntu)<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: QT_QTOPENGL_LIBRARY (ADVANCED) ", try editing CMakeCache.txt and setting QT_QTOPENGL_LIBRARY:FILEPATH=/home/kde-devel/qt-copy/lib/libQtOpenGL.so<br />
<br />
* if you get messages as "KDE4_INSTALL_HANDBOOK() is deprecated. Remove it please. Now all is done in KDE4_CREATE_HANDBOOK." then, either find the files containing the offending line and comment it out manually, or run the following script in ~/kde/src/KDE/kdebase: [http://www.plamadeala.com/files/macros_corrector.sh macros_corrector.sh]. It will just REMOVE the line that has "kde4_create_handbook" in it from all the found files.<br />
<br />
== Running KDE 4 programs ==<br />
<br />
You can now run KDE 4 programs (e.g. kwrite) by typing:<br />
ssh -X kde-devel@localhost<br />
kwrite <br />
<br />
=== Troubleshooting ===<br />
<br />
* If you get <br />
KUniqueApplication: Cannot find the D-Bus session server<br />
check if you can access the display, e.g. type<br />
xclock<br />
and see if a clock appears on the screen.<br />
<br />
* If you get something like<br />
Error: standard icon theme "oxygen" not found!<br />
<br />
ASSERT: "!isEmpty()" in file /home/kde-devel/qt-copy/include/QtCore/../../src/corelib/tools/qlist.h, line 245<br />
Aborted (core dumped)<br />
You need to install kdebase - see above. It is enough to install the "runtime" directory from kdebase.<br />
<br />
== Generating local API documentation ==<br />
Although the API documentation for KDE is available online at [http://api.kde.org api.kde.org], it is sometimes useful to have it on your own disk, for example when you want to use [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|KDevelop]] for browsing the documentation or when you are not able to be online all the time.<br />
<br />
Be aware that generating the API documentation can take several hours and takes almost half a gigabyte of diskspace.<br />
The generation is handled by a script in {{path|kdelibs/doc/api}}, you need <tt>doxygen</tt> to be able to run it. <br />
<br />
To build the API documentation for kdelibs, type the following:<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE/kdelibs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]]<br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Repeat for other modules as desired.<br><br />
cd <module home><br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Another, even easier method involves downloading this [[Doxyfile]] to your local system. Then simply change directory to where you want to create the documentation and run<br />
<code bash><br />
% doxygen /path/to/Doxyfile<br />
</code><br />
Then review the file {{path|doxygen.log}} to see the doxygen errors and warnings. You'll find the actual documentation in the {{path|apidocs}} subdirectory.<br />
<br />
== Staying up to date ==<br />
<br />
In order to keep the kde4 installation up to date, each of the modules installed should be updated periodically. As Monday is the day for big changes in kdelibs, Tuesday may be the best day to do this. For each module checked out, run <tt>svn up</tt> and <tt>make</tt>.<br />
<br />
For example:<br />
<code bash><br />
cs kdesupport # cs is not a typo<br />
svn up<br />
cb # cb is not a typo<br />
make -j2 VERBOSE=1 && make install<br />
</code><br />
<br />
== General troubleshooting ==<br />
<br />
What can happen over time, after some <tt>svn up</tt> commands, is that some of the tools used in the KDE build chain change their output format. For example, <tt>kcfg</tt> files are read by <tt>kconfig_compiler</tt> to produce configuration dialogs. CMake cannot detect those changes, and the compilation might fail. A workaround is to always force a re-generation of all such files:<br />
find $KDE_SRC/KDE/kdebase -name "*.kcfg" | xargs touch<br />
The same applies to <tt>ui</tt> files as produced by Qt designer.<br />
<br />
== Success! ==<br />
<br />
You are now ready to start building other svn modules in the same fashion as you built kdebase, running and testing KDE4 or writing your own patches and applications.<br />
<br />
See the [[Getting Started/Set up KDE 4 for development|Set up KDE 4 for development]] tutorial for how to start KDE 4 applications and how to use KDevelop to work on them.<br />
<br />
[[Category:Build KDE]]<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=13993Development/Tutorials/Using KActions (ru)2007-09-24T16:03:42Z<p>Powerfox: Update</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Действия -- центральная концепция при реализации интерактивности программы.<br />
<br />
Например, нужно чтобы по нажатию кнопки на панели инструментов, комбинации клавиш или по выбору некоторого пункта меню очищалось текстовое поле. Всё это можно сделать с помощью одного действия {{class|KAction}}.<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Для создания действия в <tt>.cpp</tt> необходимо наличие <tt>#include <KAction></tt><br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание объекта KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действий на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("document-new"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>document-new</tt>.<br />
<br />
=====Комбинация клавиш=====<br />
<br />
Также, если ожидается что действие будет выполняться часто, с ним можно связать комбинацию клавиш. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение сигналов и слотов=====<br />
<br />
Теперь, когда параметры внешнего вида действия определены, можно связать его с методом tt>clear()</tt> объекта KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Интерфейс класса аналогичен {{qt|QAction}}, в KAction лишь добавлены специфические для KDE особенности.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit, save, и load, доступны готовые объекты KAction, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит пункт в меню File.<br />
<br />
==The Code==<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 />
<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), следует использовать KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
<ActionList name="dynamicActionlist" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
Заметьте, что таким же способом можно динамически добавлять список действий, используя тэг <tt><ActionList></tt>. Для получения более подробной информации обратитесь к документации по методу <tt>plugActionList()</tt> класса {{class|KXMLGUIClient}}. <br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы проверить её (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(ru)&diff=13386Development/Tutorials/KDE4 Porting Guide (ru)2007-08-31T16:47:31Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Введение==<br />
Цель данного урока - помочь разработчикам портировать их Qt3/KDE3 приложения на Qt4/KDE4. Портирование KDE3 приложения - очень простой процесс. На данный момент написано очень много скриптов и документации, которые могут помочь в этом.<br />
<br />
<br />
==Условные обозначения==<br />
В данном уроке использованы следующие сокращения:<br />
* {{program|program}} - исполняемый файл<br />
* {{path|path}} - путь<br />
{{path|file}} - файл<br />
* $SVN - полный путь к дереву исходных кодов KDE<br />
<br />
<br />
==CMake==<br />
В отличие от KDE3, KDE4 приложения собираются с помощью [[Development/Tutorials/CMake | CMake]]. Можно легко перейти от autotools к CMake, используя скрипт {{program|am2cmake}}, который можно найти в каталоге {{path|cmake/scripts}} модуля [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk]. Этот скрипт добавит к старым файлам сборки файлы {{path|CMakeLists.txt}}.<br />
<br />
Например, если ваш исходный код находится в {{path|/path/to/src}}, то нужно выполнить следующее:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Запустите <tt> am2cmake --help</tt>, чтобы проверить, нужен ли вам параметр <tt>--kde4</tt>.<br />
<br />
Также есть специальная утилита, анализирующая полученные {{path|CMakeList.txt}} на наличие потенциальных проблем, она называется {{program|cmakelint.pl}}. Её можно найти в {{path|$SVN/trunk/kde/kdesdk/scripts}}. Пример её использования:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Её можно запускать внутри каталога с исходниками:<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 />
Обзор перехода с Qt3 на Qt4 описан в статье Trolltech [http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"]. Этот документ содержит отличный обзор главных изменений в Qt4. Настоятельно рекомендуем с ним ознакомиться.<br />
<br />
Статья [http://doc.trolltech.com/4.2/porting4.html "Porting to Qt 4"] содержит потрясающее описание процесса портирования наряду со списком изменений в классах и функциях.<br />
<br />
Этот документ описывает утилиту {{program|qt3to4}}, созданную Trolltech, которая может помочь при портировании Qt частей кода с Qt3 на Qt4, используя совместимые функции. Запустите {{program|qt3to4}}, как показано ниже:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile может быть исходным файлом или же файлом проекта. Если вы указали файл проекта, оканчивающийся на '.pro' или '.pri', {{program|qt3to4}} портирует все файлы, данного проекта.<br />
<br />
Чтобы получить более подробную информацию, запустите {{program|qt3to4}} с параметром "--help" или посетите страницу [http://doc.trolltech.com/4.2/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"].<br />
<br />
<br />
Так же существует программа {{program|remove-qt3-support.pl}}, входящая в состав модуля {{module|kdesdk}}. Она ищет и заменяет большое количество устаревших Qt3 функций. Просто запустите эту программу в каталоге с исходным кодом без всяких параметров.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
==KDE4 API==<br />
Большая часть работы при портировании заключается в переименовании классов и заголовочных файлов. В связи с тем, что делать это вручную довольно утомительно, можно использовать скрипт {{program|adapt-to-kde4-api.pl}}, который можно найти в каталоге {{path|scripts/qt4}} модуля {{module|kdesdk}}. Он просмотрит все ваши файлы и выведет diff (различия), который можно использовать, чтобы пропатчить ваш код.<br />
<br />
Теперь когда сделаны простые замены, нужно пройтись по коду, чтобы портировать, например, на новый <tt>KAction</tt> API. Документация по всем изменениям в API может быть найдена в [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] из модуля {{module|kdelibs}}.<br />
<br />
<br />
==Qt Designer и UI файлы==<br />
Файлы ".ui", созданные с помощью Qt3 должны быть конвертированы в новый формат Qt4. Это можно сделать с помощью утилиты {{program|uic3}}, входящей в состав Qt4.<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 />
Если же вы предпочитаете графический интерфейс, то можно использовать Qt4 Designer.<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|Осторожно! При конвертировании теряются пользовательские слоты, столбцы таблиц и прочее. Так что вам потребуется восстановить это вручную.}}<br />
Также необходимо запустить программу {{program|fixuifiles}} из модуля {{module|kdesdk}}:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Вместо DCOP, используемого в KDE3, в KDE4 для взаимодействия программ друг с другом используется D-Bus. Портирование с DCOP на D-BUS является обширной темой и очень детально описано в [[Development/Tutorials/Porting_to_D-Bus|Уроке по портированию на D-Bus]].<br />
<br />
Для получения дополнительной информации обратитесь к [[Development/Tutorials#D-Bus|Уроку по D-Bus]].<br />
<br />
==Значки==<br />
<br />
Имена значков в KDE4 основаны на [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html спецификации именования значков freedesktop.org].<br />
Это означает, что, как и имена значков, входящих в KDE4 (Oxygen), так и компоненты kdelibs соответствуют данной спецификации.<br />
<br />
<br />
Для портирования имён значков с KDE3 на KDE4 запустите из корневого каталога вашего проекта скрипт [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] и следуйте инструкциям на экране.<br />
<br />
Этот скрипт автоматически конвертирует подтверждённые значки (например, с использованием KIcon или KIconLoader), пропускает значки при подтверждении пропуска и спрашивает, что делать с подтверждёнными. Так же выводится подсказка, содержащая контекст, таким образом, портирование сводится к нажатию 'y' и 'n'.<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 />
==Локализация==<br />
<br />
Чтобы создать ".pot" файл, скопируйте команды с правила 'messages' из {{path|Makefile.am}} вашего проекта в скрипт с именем {{path|Messages.sh}}. Вы можете считать, что старые переменные ($PREPARETIPS, $XGETTEXT, $podir и т.д.) по-прежнему существуют, но учтите, что между Makefile и shell-скриптами есть разница в синтаксисе.<br />
<br />
Учтите, что при использовании параметра -k с $XGETTEXT, потребуется явно указать все варианты, которые вы используете.<br />
<br />
Например, вот как можно из правила 'messages':<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 />
<br />
сделать следующий скрипт {{path|Messages.sh}}:<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 />
<br />
==Что можно, а что нельзя==<br />
* Не используйте старые классы сокетов<br />
* Не используйте {{qt3|QPtrList}}, особенно setAutoDelete() <br />
* Не используйте растровые операции.<br />
* Постарайтесь не использовать {qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Отдавайте предпочтения менеджерам компоновки (layouts)<br />
* Не используйте фреймы с рамками группировки (groupboxes), текстовыми метками (labels) или строками редактирования (lineedits), чтобы создать новый виджет. Например, вместо добавления впалой рамки (как у lineedit) к label, воспользуйтесь готовым виджетом {{class|KLineEdit}}. Или вместо того, чтобы использовать {{class|KLineEdit}} без рамки, чтобы иметь возможность копировать содержимое, воспользуйтесь {{class|KActiveLabel}}.<br />
* Не используйте рамку группировки (groupbox) без рамки, чтобы объединить виджеты! Просто воспользуйтесь менеджером компоновки (layout).<br />
<br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Дополнительные ресурсы== <br />
===Документация=== <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 />
===Где спросить=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(ru)&diff=13385Development/Tutorials/KDE4 Porting Guide (ru)2007-08-31T16:42:29Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Введение==<br />
Цель данного урока - помочь разработчикам портировать их Qt3/KDE3 приложения на Qt4/KDE4. Портирование KDE3 приложения - очень простой процесс. На данный момент написано очень много скриптов и документации, которые могут помочь в этом.<br />
<br />
<br />
==Условные обозначения==<br />
В данном уроке использованы следующие сокращения:<br />
* {{program|program}} - исполняемый файл<br />
* {{path|path}} - путь<br />
{{path|file}} - файл<br />
* $SVN - полный путь к дереву исходных кодов KDE<br />
<br />
<br />
==CMake==<br />
В отличие от KDE3, KDE4 приложения собираются с помощью [[Development/Tutorials/CMake | CMake]]. Можно легко перейти от autotools к CMake, используя скрипт {{program|am2cmake}}, который можно найти в каталоге {{path|cmake/scripts}} модуля [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk]. Этот скрипт добавит к старым файлам сборки файлы {{path|CMakeLists.txt}}.<br />
<br />
Например, если ваш исходный код находится в {{path|/path/to/src}}, то нужно выполнить следующее:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Запустите <tt> am2cmake --help</tt>, чтобы проверить, нужен ли вам параметр <tt>--kde4</tt>.<br />
<br />
Также есть специальная утилита, анализирующая полученные {{path|CMakeList.txt}} на наличие потенциальных проблем, она называется {{program|cmakelint.pl}}. Её можно найти в {{path|$SVN/trunk/kde/kdesdk/scripts}}. Пример её использования:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Её можно запускать внутри каталога с исходниками:<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 />
Обзор перехода с Qt3 на Qt4 описан в статье Trolltech [http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"]. Этот документ содержит отличный обзор главных изменений в Qt4. Настоятельно рекомендуем с ним ознакомиться.<br />
<br />
Статья [http://doc.trolltech.com/4.2/porting4.html "Porting to Qt 4"] содержит потрясающее описание процесса портирования наряду со списком изменений в классах и функциях.<br />
<br />
Этот документ описывает утилиту {{program|qt3to4}}, созданную Trolltech, которая может помочь при портировании Qt частей кода с Qt3 на Qt4, используя совместимые функции. Запустите {{program|qt3to4}}, как показано ниже:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile может быть исходным файлом или же файлом проекта. Если вы указали файл проекта, оканчивающийся на '.pro' или '.pri', {{program|qt3to4}} портирует все файлы, данного проекта.<br />
<br />
Чтобы получить более подробную информацию, запустите {{program|qt3to4}} с параметром "--help" или посетите страницу [http://doc.trolltech.com/4.2/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"].<br />
<br />
<br />
Так же существует программа {{program|remove-qt3-support.pl}}, входящая в состав модуля {{module|kdesdk}}. Она ищет и заменяет большое количество устаревших Qt3 функций. Просто запустите эту программу в каталоге с исходным кодом без всяких параметров.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
==KDE4 API==<br />
Большая часть работы при портировании заключается в переименовании классов и заголовочных файлов. В связи с тем, что делать это вручную довольно утомительно, можно использовать скрипт {{program|adapt-to-kde4-api.pl}}, который можно найти в каталоге {{path|scripts/qt4}} модуля {{module|kdesdk}}. Он просмотрит все ваши файлы и выведет diff (различия), который можно использовать, чтобы пропатчить ваш код.<br />
<br />
Теперь когда сделаны простые замены, нужно пройтись по коду, чтобы портировать, например, на новый <tt>KAction</tt> API. Документация по всем изменениям в API может быть найдена в [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] из модуля {{module|kdelibs}}.<br />
<br />
<br />
==Qt Designer и UI файлы==<br />
Файлы ".ui", созданные с помощью Qt3 должны быть конвертированы в новый формат Qt4. Это можно сделать с помощью утилиты {{program|uic3}}, входящей в состав Qt4.<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 />
Если же вы предпочитаете графический интерфейс, то можно использовать Qt4 Designer.<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|Осторожно! При конвертировании теряются пользовательские слоты, столбцы таблиц и прочее. Так что вам потребуется восстановить это вручную.<br />
Также необходимо запустить программу {{program|fixuifiles}} из модуля {{module|kdesdk}}:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Вместо DCOP, используемого в KDE3, в KDE4 для взаимодействия программ друг с другом используется D-Bus. Портирование с DCOP на D-BUS является обширной темой и очень детально описано в [[Development/Tutorials/Porting_to_D-Bus|Уроке по портированию на D-Bus]].<br />
<br />
Для получения дополнительной информации обратитесь к [[Development/Tutorials#D-Bus|Уроку по D-Bus]].<br />
<br />
==Значки==<br />
<br />
Имена значков в KDE4 основаны на [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html спецификации именования значков freedesktop.org].<br />
Это означает, что, как и имена значков, входящих в KDE4 (Oxygen), так и компоненты kdelibs соответствуют данной спецификации.<br />
<br />
<br />
Для портирования имён значков с KDE3 на KDE4 запустите из корневого каталога вашего проекта скрипт [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] и следуйте инструкциям на экране.<br />
<br />
Этот скрипт автоматически конвертирует подтверждённые значки (например, с использованием KIcon или KIconLoader), пропускает значки при подтверждении пропуска и спрашивает, что делать с подтверждёнными. Так же выводится подсказка, содержащая контекст, таким образом, портирование сводится к нажатию 'y' и 'n'.<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 />
==Локализация==<br />
<br />
Чтобы создать ".pot" файл, скопируйте команды с правила 'messages' из {{path|Makefile.am}} вашего проекта в скрипт с именем {{path|Messages.sh}}. Вы можете считать, что старые переменные ($PREPARETIPS, $XGETTEXT, $podir и т.д.) по-прежнему существуют, но учтите, что между Makefile и shell-скриптами есть разница в синтаксисе.<br />
<br />
Учтите, что при использовании параметра -k с $XGETTEXT, потребуется явно указать все варианты, которые вы используете.<br />
<br />
Например, вот как можно из правила 'messages':<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 />
<br />
сделать следующий скрипт {{path|Messages.sh}}:<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 />
<br />
==Что можно, а что нельзя==<br />
* Не используйте старые классы сокетов<br />
* Не используйте {{qt3|QPtrList}}, особенно setAutoDelete() <br />
* Не используйте растровые операции.<br />
* Постарайтесь не использовать {qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Отдавайте предпочтения менеджерам компоновки (layouts)<br />
* Не используйте фреймы с рамками группировки (groupboxes), текстовыми метками (labels) или строками редактирования (lineedits), чтобы создать новый виджет. Например, вместо добавления впалой рамки (как у lineedit) к label, воспользуйтесь готовым виджетом {{class|KLineEdit}}. Или вместо того, чтобы использовать {{class|KLineEdit}} без рамки, чтобы иметь возможность копировать содержимое, воспользуйтесь {{class|KActiveLabel}}.<br />
* Не используйте рамку группировки (groupbox) без рамки, чтобы объединить виджеты! Просто воспользуйтесь менеджером компоновки (layout).<br />
<br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Дополнительные ресурсы== <br />
===Документация=== <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 />
===Где спросить=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(ru)&diff=13384Development/Tutorials/KDE4 Porting Guide (ru)2007-08-31T16:41:28Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Введение==<br />
Цель данного урока - помочь разработчикам портировать их Qt3/KDE3 приложения на Qt4/KDE4. Портирование KDE3 приложения - очень простой процесс. На данный момент написано очень много скриптов и документации, которые могут помочь в этом.<br />
<br />
<br />
==Условные обозначения==<br />
В данном уроке использованы следующие сокращения:<br />
* {{program|program}} - исполняемый файл<br />
* {{path|path}} - путь<br />
{{path|file}} - файл<br />
* $SVN - полный путь к дереву исходных кодов KDE<br />
<br />
<br />
==CMake==<br />
В отличие от KDE3, KDE4 приложения собираются с помощью [[Development/Tutorials/CMake | CMake]]. Можно легко перейти от autotools к CMake, используя скрипт {{program|am2cmake}}, который можно найти в каталоге {{path|cmake/scripts}} модуля [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk]. Этот скрипт добавит к старым файлам сборки файлы {{path|CMakeLists.txt}}.<br />
<br />
Например, если ваш исходный код находится в {{path|/path/to/src}}, то нужно выполнить следующее:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Запустите <tt> am2cmake --help</tt>, чтобы проверить, нужен ли вам параметр <tt>--kde4</tt>.<br />
<br />
Также есть специальная утилита, анализирующая полученные {{path|CMakeList.txt}} на наличие потенциальных проблем, она называется {{program|cmakelint.pl}}. Её можно найти в {{path|$SVN/trunk/kde/kdesdk/scripts}}. Пример её использования:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Её можно запускать внутри каталога с исходниками:<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 />
Обзор перехода с Qt3 на Qt4 описан в статье Trolltech [http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"]. Этот документ содержит отличный обзор главных изменений в Qt4. Настоятельно рекомендуем с ним ознакомиться.<br />
<br />
Статья [http://doc.trolltech.com/4.2/porting4.html "Porting to Qt 4"] содержит потрясающее описание процесса портирования наряду со списком изменений в классах и функциях.<br />
<br />
Этот документ описывает утилиту {{program|qt3to4}}, созданную Trolltech, которая может помочь при портировании Qt частей кода с Qt3 на Qt4, используя совместимые функции. Запустите {{program|qt3to4}}, как показано ниже:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile может быть исходным файлом или же файлом проекта. Если вы указали файл проекта, оканчивающийся на '.pro' или '.pri', {{program|qt3to4}} портирует все файлы, данного проекта.<br />
<br />
Чтобы получить более подробную информацию, запустите {{program|qt3to4}} с параметром "--help" или посетите страницу [http://doc.trolltech.com/4.2/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"].<br />
<br />
<br />
Так же существует программа {{program|remove-qt3-support.pl}}, входящая в состав модуля {{module|kdesdk}}. Она ищет и заменяет большое количество устаревших Qt3 функций. Просто запустите эту программу в каталоге с исходным кодом без всяких параметров.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
==KDE4 API==<br />
Большая часть работы при портировании заключается в переименовании классов и заголовочных файлов. В связи с тем, что делать это вручную довольно утомительно, можно использовать скрипт {{program|adapt-to-kde4-api.pl}}, который можно найти в каталоге {{path|scripts/qt4}} модуля {{module|kdesdk}}. Он просмотрит все ваши файлы и выведет diff (различия), который можно использовать, чтобы пропатчить ваш код.<br />
<br />
Теперь когда сделаны простые замены, нужно пройтись по коду, чтобы портировать, например, на новый <tt>KAction</tt> API. Документация по всем изменениям в API может быть найдена в [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] из модуля {{module|kdelibs}}.<br />
<br />
<br />
==Qt Designer и UI файлы==<br />
Файлы ".ui", созданные с помощью Qt3 должны быть конвертированы в новый формат Qt4. Это можно сделать с помощью утилиты {{program|uic3}}, входящей в состав Qt4.<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 />
Если же вы предпочитаете графический интерфейс, то можно использовать Qt4 Designer.<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|Осторожно! При конвертировании теряются пользовательские слоты, столбцы таблиц и прочее. Так что вам потребуется восстановить это вручную.<br />
Также необходимо запустить программу {{program|fixuifiles}} из модуля {{module|kdesdk}}:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Вместо DCOP, используемого в KDE3, в KDE4 для взаимодействия программ друг с другом используется D-Bus. Портирование с DCOP на D-BUS является обширной темой и очень детально описано в [[Development/Tutorials/Porting_to_D-Bus|Уроке по портированию на D-Bus]].<br />
<br />
Для получения дополнительной информации обратитесь к [[Development/Tutorials#D-Bus|Уроку по D-Bus]].<br />
<br />
Значки<br />
<br />
Имена значков в KDE4 основаны на [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html спецификации именования значков freedesktop.org].<br />
Это означает, что, как и имена значков, входящих в KDE4 (Oxygen), так и компоненты kdelibs соответствуют данной спецификации.<br />
<br />
<br />
Для портирования имён значков с KDE3 на KDE4 запустите из корневого каталога вашего проекта скрипт [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] и следуйте инструкциям на экране.<br />
<br />
Этот скрипт автоматически конвертирует подтверждённые значки (например, с использованием KIcon или KIconLoader), пропускает значки при подтверждении пропуска и спрашивает, что делать с подтверждёнными. Так же выводится подсказка, содержащая контекст, таким образом, портирование сводится к нажатию 'y' и 'n'.<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 />
==Локализация==<br />
<br />
Чтобы создать ".pot" файл, скопируйте команды с правила 'messages' из {{path|Makefile.am}} вашего проекта в скрипт с именем {{path|Messages.sh}}. Вы можете считать, что старые переменные ($PREPARETIPS, $XGETTEXT, $podir и т.д.) по-прежнему существуют, но учтите, что между Makefile и shell-скриптами есть разница в синтаксисе.<br />
<br />
Учтите, что при использовании параметра -k с $XGETTEXT, потребуется явно указать все варианты, которые вы используете.<br />
<br />
Например, вот как можно из правила 'messages':<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 />
<br />
сделать следующий скрипт {{path|Messages.sh}}:<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 />
<br />
==Что можно, а что нельзя==<br />
* Не используйте старые классы сокетов<br />
* Не используйте {{qt3|QPtrList}}, особенно setAutoDelete() <br />
* Не используйте растровые операции.<br />
* Постарайтесь не использовать {qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Отдавайте предпочтения менеджерам компоновки (layouts)<br />
* Не используйте фреймы с рамками группировки (groupboxes), текстовыми метками (labels) или строками редактирования (lineedits), чтобы создать новый виджет. Например, вместо добавления впалой рамки (как у lineedit) к label, воспользуйтесь готовым виджетом {{class|KLineEdit}}. Или вместо того, чтобы использовать {{class|KLineEdit}} без рамки, чтобы иметь возможность копировать содержимое, воспользуйтесь {{class|KActiveLabel}}.<br />
* Не используйте рамку группировки (groupbox) без рамки, чтобы объединить виджеты! Просто воспользуйтесь менеджером компоновки (layout).<br />
<br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Дополнительные ресурсы== <br />
===Документация=== <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 />
===Где спросить=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(ru)&diff=13383Development/Tutorials/KDE4 Porting Guide (ru)2007-08-31T16:36:12Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Введение==<br />
Цель данного урока - помочь разработчикам портировать их Qt3/KDE3 приложения на Qt4/KDE4. Портирование KDE3 приложения - очень простой процесс. На данный момент написано очень много скриптов и документации, которые могут помочь в этом.<br />
<br />
<br />
==Условные обозначения==<br />
В данном уроке использованы следующие сокращения:<br />
* {{program|program}} - исполняемый файл<br />
* {{path|path}} - путь<br />
{{path|file}} - файл<br />
* $SVN - полный путь к дереву исходных кодов KDE<br />
<br />
<br />
==CMake==<br />
В отличие от KDE3, KDE4 приложения собираются с помощью [[Development/Tutorials/CMake | CMake]]. Можно легко перейти от autotools к CMake, используя скрипт {{program|am2cmake}}, который можно найти в каталоге {{path|cmake/scripts}} модуля [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk]. Этот скрипт добавит к старым файлам сборки файлы {{path|CMakeLists.txt}}.<br />
<br />
Например, если ваш исходный код находится в {{path|/path/to/src}}, то нужно выполнить следующее:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Запустите <tt> am2cmake --help</tt>, чтобы проверить, нужен ли вам параметр <tt>--kde4</tt>.<br />
<br />
Также есть специальная утилита, анализирующая полученные {{path|CMakeList.txt}} на наличие потенциальных проблем, она называется {{program|cmakelint.pl}}. Её можно найти в {{path|$SVN/trunk/kde/kdesdk/scripts}}. Пример её использования:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Её можно запускать внутри каталога с исходниками:<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 />
Обзор перехода с Qt3 на Qt4 описан в статье Trolltech [http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"]. Этот документ содержит отличный обзор главных изменений в Qt4. Настоятельно рекомендуем с ним ознакомиться.<br />
<br />
Статья [http://doc.trolltech.com/4.2/porting4.html "Porting to Qt 4"] содержит потрясающее описание процесса портирования наряду со списком изменений в классах и функциях.<br />
<br />
Этот документ описывает утилиту {{program|qt3to4}}, созданную Trolltech, которая может помочь при портировании Qt частей кода с Qt3 на Qt4, используя совместимые функции. Запустите {{program|qt3to4}}, как показано ниже:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile может быть исходным файлом или же файлом проекта. Если вы указали файл проекта, оканчивающийся на '.pro' или '.pri', {{program|qt3to4}} портирует все файлы, данного проекта.<br />
<br />
Чтобы получить более подробную информацию, запустите {{program|qt3to4}} с параметром "--help" или посетите страницу [http://doc.trolltech.com/4.2/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"].<br />
<br />
<br />
Так же существует программа {{program|remove-qt3-support.pl}}, входящая в состав модуля {{module|kdesdk}}. Она ищет и заменяет большое количество устаревших Qt3 функций. Просто запустите эту программу в каталоге с исходным кодом без всяких параметров.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
==KDE4 API==<br />
Большая часть работы при портировании заключается в переименовании классов и заголовочных файлов. В связи с тем, что делать это вручную довольно утомительно, можно использовать скрипт {{program|adapt-to-kde4-api.pl}}, который можно найти в каталоге {{path|scripts/qt4}} модуля {{module|kdesdk}}. Он просмотрит все ваши файлы и выведет diff (различия), который можно использовать, чтобы пропатчить ваш код.<br />
<br />
Теперь когда сделаны простые замены, нужно пройтись по коду, чтобы портировать, например, на новый <tt>KAction</tt> API. Документация по всем изменениям в API может быть найдена в [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] из модуля {{module|kdelibs}}.<br />
<br />
<br />
==Qt Designer и UI файлы==<br />
Файлы ".ui", созданные с помощью Qt3 должны быть конвертированы в новый формат Qt4. Это можно сделать с помощью утилиты {{program|uic3}}, входящей в состав Qt4.<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 />
Если же вы предпочитаете графический интерфейс, то можно использовать Qt4 Designer.<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|Осторожно! При конвертировании теряются пользовательские слоты, столбцы таблиц и прочее. Так что вам потребуется восстановить это вручную.<br />
Также необходимо запустить программу {{program|fixuifiles}} из модуля {{module|kdesdk}}:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Вместо DCOP, используемого в KDE3, в KDE4 для взаимодействия программ друг с другом используется D-Bus. Портирование с DCOP на D-BUS является обширной темой и очень детально описано в [[Development/Tutorials/Porting_to_D-Bus|Уроке по портированию на D-Bus]].<br />
<br />
Для получения дополнительной информации обратитесь к [[Development/Tutorials#D-Bus|Уроку по D-Bus]].<br />
<br />
==Значки==<br />
Имена значков в KDE4 основаны на [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html спецификации именования значков freedesktop.org].<br />
Это означает, что, как и имена значков, входящих в KDE4 (Oxygen), так и компоненты kdelibs соответствуют данной спецификации.<br />
<br />
<br />
Для портирования имён значков с KDE3 на KDE4 запустите из корневого каталога вашего проекта скрипт [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] и следуйте инструкциям на экране.<br />
<br />
Этот скрипт автоматически конвертирует подтверждённые значки (например, с использованием KIcon или KIconLoader), пропускает значки при подтверждении пропуска и спрашивает, что делать с подтверждёнными. Так же выводится подсказка, содержащая контекст, таким образом, портирование сводится к нажатию 'y' и 'n'.<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 />
==Локализация==<br />
Чтобы создать ".pot" файл, скопируйте команды с правила 'messages' из {{path|Makefile.am}} вашего проекта в скрипт с именем {{path|Messages.sh}}. Вы можете считать, что старые переменные ($PREPARETIPS, $XGETTEXT, $podir и т.д.) по-прежнему существуют, но учтите, что между Makefile и shell-скриптами есть разница в синтаксисе.<br />
<br />
Учтите, что при использовании параметра -k с $XGETTEXT, потребуется явно указать все варианты, которые вы используете.<br />
<br />
Например, вот как можно из правила 'messages':<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 />
<br />
сделать следующий скрипт {{path|Messages.sh}}:<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 />
<br />
==Что можно, а что нельзя==<br />
* Не используйте старые классы сокетов<br />
* Не используйте {{qt3|QPtrList}}, особенно setAutoDelete() <br />
* Не используйте растровые операции.<br />
* Постарайтесь не использовать {qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Отдавайте предпочтения менеджерам компоновки (layouts)<br />
* Не используйте фреймы с рамками группировки (groupboxes), текстовыми метками (labels) или строками редактирования (lineedits), чтобы создать новый виджет. Например, вместо добавления впалой рамки (как у lineedit) к label, воспользуйтесь готовым виджетом {{class|KLineEdit}}. Или вместо того, чтобы использовать {{class|KLineEdit}} без рамки, чтобы иметь возможность копировать содержимое, воспользуйтесь {{class|KActiveLabel}}.<br />
* Не используйте рамку группировки (groupbox) без рамки, чтобы объединить виджеты! Просто воспользуйтесь менеджером компоновки (layout).<br />
<br />
* Do NOT use a groupbox without border to group widgets! Just use a layout.<br />
<br />
==Дополнительные ресурсы== <br />
===Документация=== <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 />
===Где спросить=== <br />
* #kde4-devel on irc.freenode.net <br />
<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide_(ru)&diff=13382Development/Tutorials/KDE4 Porting Guide (ru)2007-08-31T16:34:50Z<p>Powerfox: Added Russian translation</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Введение==<br />
Цель данного урока - помочь разработчикам портировать их Qt3/KDE3 приложения на Qt4/KDE4. Портирование KDE3 приложения - очень простой процесс. На данный момент написано очень много скриптов и документации, которые могут помочь в этом.<br />
<br />
<br />
==Условные обозначения==<br />
В данном уроке использованы следующие сокращения:<br />
* {{program|program}} - исполняемый файл<br />
* {{path|path}} - путь<br />
{{path|file}} - файл<br />
* $SVN - полный путь к дереву исходных кодов KDE<br />
<br />
<br />
==CMake==<br />
В отличие от KDE3, KDE4 приложения собираются с помощью [[Development/Tutorials/CMake | CMake]]. Можно легко перейти от autotools к CMake, используя скрипт {{program|am2cmake}}, который можно найти в каталоге {{path|cmake/scripts}} модуля [http://websvn.kde.org/trunk/KDE/kdesdk/ kdesdk]. Этот скрипт добавит к старым файлам сборки файлы {{path|CMakeLists.txt}}.<br />
<br />
Например, если ваш исходный код находится в {{path|/path/to/src}}, то нужно выполнить следующее:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/cmake/scripts/am2cmake --kde4<br />
</code><br />
Запустите <tt> am2cmake --help</tt>, чтобы проверить, нужен ли вам параметр <tt>--kde4</tt>.<br />
<br />
Также есть специальная утилита, анализирующая полученные {{path|CMakeList.txt}} на наличие потенциальных проблем, она называется {{program|cmakelint.pl}}. Её можно найти в {{path|$SVN/trunk/kde/kdesdk/scripts}}. Пример её использования:<br />
<code bash><br />
% cd /path/to/src<br />
% $SVN/trunk/KDE/kdesdk/scripts/cmakelint.pl CMakeLists.txt<br />
</code><br />
Её можно запускать внутри каталога с исходниками:<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 />
Обзор перехода с Qt3 на Qt4 описан в статье Trolltech [http://www.trolltech.com/products/qt/whatsnew/porting "Moving from Qt 3 to Qt 4"]. Этот документ содержит отличный обзор главных изменений в Qt4. Настоятельно рекомендуем с ним ознакомиться.<br />
<br />
Статья [http://doc.trolltech.com/4.2/porting4.html "Porting to Qt 4"] содержит потрясающее описание процесса портирования наряду со списком изменений в классах и функциях.<br />
<br />
Этот документ описывает утилиту {{program|qt3to4}}, созданную Trolltech, которая может помочь при портировании Qt частей кода с Qt3 на Qt4, используя совместимые функции. Запустите {{program|qt3to4}}, как показано ниже:<br />
<code bash><br />
% $SVN/trunk/qt-copy/bin/qt3to4 [options] <Infile>, [Infile], ...<br />
</code><br />
Infile может быть исходным файлом или же файлом проекта. Если вы указали файл проекта, оканчивающийся на '.pro' или '.pri', {{program|qt3to4}} портирует все файлы, данного проекта.<br />
<br />
Чтобы получить более подробную информацию, запустите {{program|qt3to4}} с параметром "--help" или посетите страницу [http://doc.trolltech.com/4.2/qt3to4.html "qt3to4-The Qt 3 to 4 Porting Tool"].<br />
<br />
<br />
Так же существует программа {{program|remove-qt3-support.pl}}, входящая в состав модуля {{module|kdesdk}}. Она ищет и заменяет большое количество устаревших Qt3 функций. Просто запустите эту программу в каталоге с исходным кодом без всяких параметров.<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/qt4/remove-qt3-support.pl<br />
</code><br />
<br />
==KDE4 API==<br />
Большая часть работы при портировании заключается в переименовании классов и заголовочных файлов. В связи с тем, что делать это вручную довольно утомительно, можно использовать скрипт {{program|adapt-to-kde4-api.pl}}, который можно найти в каталоге {{path|scripts/qt4}} модуля {{module|kdesdk}}. Он просмотрит все ваши файлы и выведет diff (различия), который можно использовать, чтобы пропатчить ваш код.<br />
<br />
Теперь когда сделаны простые замены, нужно пройтись по коду, чтобы портировать, например, на новый <tt>KAction</tt> API. Документация по всем изменениям в API может быть найдена в [http://websvn.kde.org/*checkout*/trunk/KDE/kdelibs/KDE4PORTING.html KDE4PORTING.html] из модуля {{module|kdelibs}}.<br />
<br />
<br />
==Qt Designer и UI файлы==<br />
Файлы ".ui", созданные с помощью Qt3 должны быть конвертированы в новый формат Qt4. Это можно сделать с помощью утилиты {{program|uic3}}, входящей в состав Qt4.<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 />
Если же вы предпочитаете графический интерфейс, то можно использовать Qt4 Designer.<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|Осторожно! При конвертировании теряются пользовательские слоты, столбцы таблиц и прочее. Так что вам потребуется восстановить это вручную.<br />
Также необходимо запустить программу {{program|fixuifiles}} из модуля {{module|kdesdk}}:<br />
<code bash><br />
% $SVN/trunk/KDE/kdesdk/scripts/fixuifiles<br />
</code><br />
<br />
==D-Bus==<br />
Вместо DCOP, используемого в KDE3, в KDE4 для взаимодействия программ друг с другом используется D-Bus. Портирование с DCOP на D-BUS является обширной темой и очень детально описано в [[Development/Tutorials/Porting_to_D-Bus|Уроке по портированию на D-Bus]].<br />
<br />
Для получения дополнительной информации обратитесь к [[Development/Tutorials#D-Bus|Уроку по D-Bus]].<br />
<br />
==Значки==<br />
Имена значков в KDE4 основаны на [http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html спецификации именования значков freedesktop.org].<br />
Это означает, что, как и имена значков, входящих в KDE4 (Oxygen), так и компоненты kdelibs соответствуют данной спецификации.<br />
<br />
<br />
Для портирования имён значков с KDE3 на KDE4 запустите из корневого каталога вашего проекта скрипт [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/qt4/adapt-to-icon-spec.py adapt-to-icon-spec.py] и следуйте инструкциям на экране.<br />
<br />
Этот скрипт автоматически конвертирует подтверждённые значки (например, с использованием KIcon или KIconLoader), пропускает значки при подтверждении пропуска и спрашивает, что делать с подтверждёнными. Так же выводится подсказка, содержащая контекст, таким образом, портирование сводится к нажатию 'y' и 'n'.<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 />
==Локализация==<br />
Чтобы создать ".pot" файл, скопируйте команды с правила 'messages' из {{path|Makefile.am}} вашего проекта в скрипт с именем {{path|Messages.sh}}. Вы можете считать, что старые переменные ($PREPARETIPS, $XGETTEXT, $podir и т.д.) по-прежнему существуют, но учтите, что между Makefile и shell-скриптами есть разница в синтаксисе.<br />
<br />
Учтите, что при использовании параметра -k с $XGETTEXT, потребуется явно указать все варианты, которые вы используете.<br />
<br />
Например, вот как можно из правила 'messages':<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 />
<br />
сделать следующий скрипт {{path|Messages.sh}}:<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 />
<br />
==Что можно, а что нельзя==<br />
* Не используйте старые классы сокетов<br />
* Не используйте {{qt3|QPtrList}}, особенно setAutoDelete() <br />
* Не используйте растровые операции.<br />
* Постарайтесь не использовать {qt3|QHBox}}, {{qt3|QVBox}}, {{qt3|QGrid}}. Отдавайте предпочтения менеджерам компоновки (layouts)<br />
* Не используйте фреймы с рамками группировки (groupboxes), текстовыми метками (labels) или строками редактирования (lineedits), чтобы создать новый виджет. Например, вместо добавления впалой рамки (как у lineedit) к label, воспользуйтесь готовым виджетом {{class|KLineEdit}}. Или вместо того, чтобы использовать {{class|KLineEdit}} без рамки, чтобы иметь возможность копировать содержимое, воспользуйтесь {{class|KActiveLabel}}.<br />
* Не используйте рамку группировки (groupbox) без рамки, чтобы объединить виджеты! Просто воспользуйтесь менеджером компоновки (layout).<br />
<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>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide&diff=13381Development/Tutorials/KDE4 Porting Guide2007-08-31T16:28:24Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Introduction==<br />
A tutorial intended to help developers port their Qt3/KDE3 based applications to Qt4/KDE4. Porting a KDE3 based application needn't be a difficult process. Already, there are many scripts and sources of documentation which can help.<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/4.2/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/4.2/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 />
==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:<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 explicitely 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>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/KDE4_Porting_Guide&diff=13380Development/Tutorials/KDE4 Porting Guide2007-08-31T16:27:58Z<p>Powerfox: Added Language Navigation Bar</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|GDevelopment/Tutorials/KDE4_Porting_Guide}}<br />
<br />
==Introduction==<br />
A tutorial intended to help developers port their Qt3/KDE3 based applications to Qt4/KDE4. Porting a KDE3 based application needn't be a difficult process. Already, there are many scripts and sources of documentation which can help.<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/4.2/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/4.2/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 />
==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:<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 explicitely 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>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/First_program_(ru)&diff=13273Development/Tutorials/First program (ru)2007-08-28T21:51:16Z<p>Powerfox: Link update</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/First_program}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Hello World|<br />
<br />
pre=[http://mindview.net/Books/TICPP/ThinkingInCPP2e.html C++], [http://www.trolltech.com/products/qt/ Qt], [[Getting_Started/Build/KDE4_(ru)|Сборка и настройка KDE4]]|<br />
<br />
next=[[Development/Tutorials/Using_KXmlGuiWindow_%28ru%29|Урок 2 - KXmlGuiWindow]]| <br />
<br />
reading=[[Development/Tutorials/CMake|CMake]]<br />
}}<br />
<br />
==Введение==<br />
Первая программа приветствует мир дружелюбным "Hello World". Для этого будет использован {{class|KMessageBox}} с изменением одной из кнопок.<br />
[[image:introtokdetutorial1.png|frame|center]]<br />
<br />
{{tip|Для получения большей информации о каком-либо классе, с которым вы работаете, Konqueror предоставляет возможность быстрого вызова справки. Таким образом, чтобы посмотреть информацию о KMessageBox, просто введите "kde:kmessagebox" в Konqueror, и будет открыта документация.}}<br />
<br />
{{tip|<br />
Для работы с проектами можно использовать KDevelop, имеющий такие функции, как дополнение кода, лёгкий доступ к документации по API или поддержка отладки, удобство которых вы обязательно оцените после получения минимального опыта программирования.<br />
<br />
В [[Getting_Started/Set_up_KDE_4_for_development_(ru)#KDevelop|этом документе]] описывается настройка KDevelop для данной задачи. Проверить, работают ли настройки, можно попробовав открыть проект существующего приложения KDE4 с помощью KDevelop.<br />
<br />
Тем не менее, файлы CMake по-прежнему нужно редактировать вручную.<br />
}}<br />
<br />
==Код==<br />
Весь необходимый код находится в <tt>main.cpp</tt>. Создайте файл с кодом, приведённым ниже:<br />
<code cppqt><br />
#include <QString><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KMessageBox><br />
#include <KCmdLineArgs><br />
#include <KLocalizedString><br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData("tutorial1", // Имя программы используется для внутренних нужд.<br />
0, // Имя директории с сообщением (The message catalog name), используется имя программы, если 0.<br />
ki18n("Tutorial 1"), // Отображаемое имя программы.<br />
"1.0", // Строка с информацией о версии программы.<br />
ki18n("KMessageBox popup"), // Краткое описание того, что делает программа.<br />
KAboutData::License_GPL, // Тип лицензии.<br />
ki18n("(c) 2007"), // Заявление об авторском праве.<br />
ki18n("Some text..."), // Произвольный текст, содержащий информацию любого рода.<br />
"http://tutorial.com", // Адрес домашней страницы программы<br />
"submit@bugs.kde.org"); // Строка с адресом электронной почты для сообщений об ошибках.<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 />
<br />
Первый KDE код, который был встречен в программе - {{class|KAboutData}}. Это специальный класс для хранения такой информации о программе, как краткое описание, авторы, тип лицензии. Почти каждое (Pretty much) KDE-приложение должно использовать этот класс.<br />
<br />
Затем был использован {{class|KCmdLineArgs}}. Этот класс позволяет задать параметры командной строки, например, чтобы запускать программу с заданным файлом. Однако, в этом туториале мы просто инициализировали этот класс с помощью созданного объекта {{class|KAboutData}}. Так что можно использовать параметры командной строки <tt>--version</tt> or <tt>--author</tt>.<br />
<br />
В строке 13 был создан объект {{class|KApplication}}. Он нужен для таких вещей, как [[Development/Tutorials/Localization/i18n|поддержка перевода программ на другие языки]].<br />
<br />
Теперь, когда все требуемые начальные действия относящиеся к KDE выполнены, можно перейти к созданию интересных вещей для нашего приложения. Мы собираемся сделать всплывающее окно (popup box), кроме того, мы изменим одну из кнопок. Чтобы это сделать, нужен объект {{class|KGuiItem}}. Первый аргумент в конструкторе {{class|KGuiItem}} - текст, который отображается на элементе (в нашем случае - кнопке). Следующий параметр - значок для кнопки, но нам это не нужно, поэтому мы опускаем его, написав <tt>QString()</tt>. Наконец, мы задаём текст всплывающей подсказки (который появляется при наведении курсора на элемент) и текст для "What's This(Что это такое)?" (доступно через правый щелчок мышью или же Shift-F1)<br />
<br />
Теперь элемент настроен, и мы можем создать всплывающее окно (popup). Для этого вызывается функция <tt>KMessageBox::questionYesNo()</tt>, которая по умолчанию создаёт MessageBox с кнопками "Да", "Нет". Второй аргумент - текст, который будет выведен посередине диалогового окна.<br />
Третий - заголовок, который будет задан для окна и, наконец, мы используем KGuiItem (что будет нормально работать) для кнопки "Да" в <tt>KGuiItem guiItem</tt>, который нами создан.<br />
<br />
Теперь, когда мы закончили ознакомление с кодом, время собрать и запустить наше приложение.<br />
<br />
==Сборка==<br />
Если системное окружение было настроена так, как описано в [[Getting_Started/Build/KDE4|Getting_Started/Build/Unstable_Version]], то код можно скомпилировать так:<br />
<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 />
А затем запустить с помощью <br />
dbus-launch ./tutorial1<br />
<br />
===Использование CMake===<br />
Процесс сборки автоматизируется с помощью [[Development/Tutorials/CMake|CMake]]. Он самостоятельно определяет расположение библиотек и заголовочных файлов KDE, Qt и др. Использование CMake упрощает сборку приложения на другом компьютере.<br />
<br />
====CMakeLists.txt====<br />
Создайте файл с именем CMakeLists.txt со следующим содержанием в той же директории, что и main.cpp <br />
<code><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 />
<br />
Функция <tt>find_package()</tt> находит заданный пакет (в данном случае KDE4) и устанавливает определённые переменные, описывающие расположение заголовков и библиотек пакета. В данном примере использована переменная <tt>KDE4_INCLUDES</tt>, которая содержит путь к заголовочным файлам KDE4.<br />
<br />
Чтобы компилятор нашёл эти файлы, нужно передать эту переменную функции <tt>include_directories()</tt>, которая добавит директорию с заголовками KDE4 в поиск (search path).<br />
<br />
Далее была создана переменная <tt>tutorial1_SRCS</tt>, инициализированная с помощью функции <tt>set()</tt>. В данном случае, ей было просто задано имя исходного файла.<br />
<br />
Затем была использована функция <tt>kde4_add_executable()</tt>, чтобы создать исполняемый файл <tt>tutorial1</tt> из исходных файлов, перечисленных в переменной <tt>tutorial1_SRCS</tt>. Наконец, указывается библиотека KDE4 kdeui для линковки с файлом с помощью <tt>target_link_libraries()</tt> и переменной <tt>KDE4_KDEUI_LIBS</tt>, заданной с помощью функции <tt>find_package()</tt>.<br />
<br />
====Выполнение сборки и запуск (Make and Run)====<br />
Опять же, если системное окружение было установлено так, как описано в [[Getting_Started/Build/KDE4|Getting_Started/Build/Unstable_Version]], данный исходный код можно скомпилировать с помощью<br />
cmakekde<br />
<br />
И запустить<br />
./tutorial1.shell<br />
<br />
==Продолжим изучение==<br />
Теперь можно перейти к [[Development/Tutorials/Using_KXmlGuiWindow|статье о KXmlGuiWindow]].<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4&diff=13234Getting Started/Build/KDE42007-08-27T13:17:04Z<p>Powerfox: /* Setting up the environment */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Getting Started|<br />
<br />
name=Building KDE4 From Source|<br />
<br />
pre=[[../../Sources/Anonymous_SVN|Anonymous SVN Quickstart Guide]]|<br />
<br />
next=[[../../Set_up_KDE_4_for_development|Set up KDE 4 for development]]|<br />
<br />
reading=[http://kdesvn-build.kde.org/ kdesvn-build: The KDE From Subversion Build Tool]<br>[[../../Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br>[[Development/Tutorials/CMake |Introduction to CMake]]<br>[[../KDE4/FreeBSD|FreeBSD notes]]<br>[[../KDE4/Mac OS X|Instructions for Mac OS X]]<br>[[../KDE4/Windows|Instructions for MS Windows]]|<br />
}}<br />
<br />
== Abstract ==<br />
<br />
This tutorial shows one way to get KDE from trunk running on Linux/BSD systems. There are also tutorials for [[/FreeBSD|FreeBSD]], [http://www.kdelibs.com/ Windows], [[/Mac OS X|Mac OS X]] and [http://solaris.kde.org/ Solaris]. Throughout the tutorial the bash shell is used.<br />
<br />
{{warning|Expect a higher risk of build failure '''on Mondays''' when most kdelibs changes are committed. [http://developer.kde.org/~dirk/dashboard/ Dashboard] reports unexpected breakages. You are encouraged to fix failing modules.<br />
}}<br />
<br />
== Required Software ==<br />
<br />
The following must be installed first before you can successfully complete this tutorial:<br />
* gcc and g++ from the gcc project, preferably version 4.1 or higher<br />
* svn, the subversion revision control client<br />
* pkg-config<br />
* development libraries and headers for X11, OpenGL (mesa-common-dev and libglu1-mesa-dev), libjpeg, libpng, libungif, [http://clucene.sourceforge.net/index.php/Downloads libclucene], [http://download.librdf.org/source/ librdf], libxml2 and libxslt<br />
* the <tt>makeobj</tt> script, which is part of kdesdk. You can install it as part of kdesdk (kdesdk-scripts on Debian) or similar package, or just download it itself from [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/makeobj WebSVN]<br />
* the [http://freedesktop.org/wiki/Software/shared-mime-info shared-mime-info package], which is the freedesktop MIME standard KDE is using now<br />
* [http://boost.org/ boost], needed by kdebase; after compiling and/or installing boost, in order to make cmake aware about its location (FindBoost), add boost directory (the one containing include subdirectory) to CMAKE_INCLUDE_PATH or set an environment variable called BOOST_ROOT pointing to boost directory.<br />
<br />
=== Ark Linux ===<br />
In Ark Linux, the build dependencies you need are installed with:<br />
<br />
<code bash><br />
apt-get install devel-core libxml-devel libxslt-devel bzip2-devel \<br />
clucene-devel librdf-devel shared-mime-info xorg-Mesa-libGL-devel \<br />
subversion boost-devel doxygen giflib-devel dbus-devel openssl-devel \<br />
alsa-lib-devel kdesdk-scripts qt4-devel<br />
</code><br />
<br />
If you prefer a graphical interface, select the packages listed above in the "Install Software" tool in Mission Control.<br />
<br />
This includes installation of CMake, DBus and Qt - you can skip steps 5, 6 and 7.<br />
<br />
=== Kubuntu ===<br />
<br />
In Kubuntu 7.04 (Feisty) the build dependencies you need are installed with:<br />
<code bash><br />
sudo aptitude install build-essential cdbs debhelper cmake \<br />
libxml2-dev libxslt1-dev libbz2-dev libclucene-dev librdf-dev \<br />
shared-mime-info libgl1-mesa-dev libglu1-mesa-dev mesa-common-dev \<br />
libxext-dev libjpeg-dev libpng-dev subversion libsm-dev libxinerama-dev \<br />
libxrender-dev libfontconfig-dev libboost-dev libxcursor-dev doxygen \<br />
libungif4-dev libdbus-1-dev libgpgme11-dev libssl-dev libgpgme11-dev \<br />
libasound2-dev kdesdk-scripts<br />
</code><br />
<br />
You can skip the manual installation of CMake 2.4.6 and DBus with: <br />
<code bash><br />
sudo aptitude install libdbus-1-dev cmake<br />
</code><br />
<br />
For a fully functional API documentation framework you also need:<br />
<code bash><br />
sudo aptitude install graphviz<br />
</code><br />
<br />
=== openSUSE ===<br />
<br />
In openSUSE 10.2 and newer, you can install packages using [http://en.opensuse.org/Zypper Zypper]:<br />
<code bash><br />
sudo zypper install <package-name><br />
</code><br />
<br />
In older releases of SUSE, you can use YaST:<br />
<code bash><br />
su<br />
yast -i <packagename><br />
</code><br />
<br />
'''Required Packages'''<br />
<br />
The packages you will need to install are:<br />
<code><br />
xorg-x11-devel<br />
libxml2-devel <br />
kdesdk3 <br />
clucene-core-devel <br />
boost-devel<br />
libjpeg-devel <br />
liblrdf-devel <br />
libpng-devel <br />
libxslt-devel <br />
libredland-devel<br />
Mesa-devel <br />
giflib-devel <br />
subversion <br />
gcc <br />
gcc-c++<br />
</code><br />
<br />
'''Optional Packages'''<br />
<br />
You can skip the manual installation of Qt 4.3, CMake 2.4.6 and DBus by installing the adding the openSUSE Build Service KDE4 Repository to your installation sources.<br />
<br />
For openSUSE 10.2 and newer do:<br />
<code><br />
sudo zypper service-add http://software.opensuse.org/download/KDE:/KDE4/openSUSE_10.2 KDE4-102<br />
</code><br />
<br />
For older versions of SUSE Linux do:<br />
<code><br />
su<br />
installation_sources -a http://software.opensuse.org/download/KDE:/KDE4/[YOUR SUSE LINUX VERSION]<br />
</code><br />
<br />
Now install the following packages (and their dependencies):<br />
<code><br />
cmake<br />
dbus-1-devel<br />
libqt4-devel<br />
</code><br />
<br />
And for fully functional apidox framework you also need:<br />
<code><br />
graphviz<br />
</code><br />
<br />
CMake binary packages for openSUSE are available from [http://software.opensuse.org/download/devel:/tools:/building/ openSUSE build service].<br />
<br />
=== Gentoo ===<br />
<br />
==== Install by hand ====<br />
<br />
You can use most stable ebuilds just remember to sync your portage before you begin.<br />
<br />
We need to be unmasked and/or kept at a lower version to continue.<br />
<br />
<code bash><br />
# echo 'x11-libs/qt' >> /etc/portage/package.unmask<br />
# echo 'dev-util/cmake' >> /etc/portage/package.unmask<br />
# echo 'dev-cpp/clucene' >> /etc/portage/package.unmask<br />
# echo '>dev-cpp/clucene-0.9.16a' >> /etc/portage/package.mask<br />
</code><br />
<br />
Make sure you have set the berkdb USE flag for redland, otherwise nepomuk won't work:<br />
<br />
<code bash><br />
# echo 'dev-libs/redland berkdb' >> /etc/portage/package.use<br />
</code><br />
<br />
<br />
These are the packages you will need to install, some may already be installed so you may skip those by adding the update flag to emerge.<br />
<br />
<code bash><br />
$ emerge -avu ebuild/name<br />
</code><br />
<br />
sys-devel/gcc<br />
dev-util/subversion<br />
dev-util/pkgconfig<br />
x11-base/xorg-x11<br />
media-libs/glut<br />
media-libs/mesa<br />
media-libs/jpeg<br />
media-libs/libpng<br />
media-libs/giflib<br />
dev-cpp/clucene<br />
dev-util/cppunit<br />
media-libs/liblrdf<br />
dev-libs/libxml2<br />
dev-libs/libxslt<br />
x11-misc/shared-mime-info<br />
kde-base/kdesdk-scripts<br />
dev-libs/boost<br />
x11-libs/qt<br />
dev-util/cmake<br />
sys-apps/dbus<br />
dev-libs/redland<br />
<br />
Provided you have emerged these ebuilds, you can skip compiling them by hand and proceed to [[Getting_Started/Build/KDE4#kdesupport|kdesupport section]].<br />
<br />
Good luck!<br />
<br />
==== Install via portage ====<br />
<br />
Also you can install the KDE 4 packages directly via <br />
<code bash><br />
emerge -a <packagename><br />
</code><br />
<br />
To get the things you need, [http://gentoo-wiki.com/TIP_Overlays#Layman install layman] and then pull in the KDE overlay (which contains experimental KDE ebuilds): <br />
<code bash><br />
layman -a kde<br />
</code><br />
After this you need to adjust some USE-flags for KDE 4 and tell portage to use the testing KDE 4 ebuilds instead of the stable KDE 3 ones. <br />
<br />
That way portage will do the dependency tracking for you. <br />
<br />
Detailed instructions on building KDE 4 in Gentoo via portage can be found in the [http://overlays.gentoo.org/proj/kde/wiki KDE overlay wiki]. They are discussed in the thread [http://forums.gentoo.org/viewtopic-t-530111-postdays-0-postorder-asc-start-0.html KDE 4 monolithic ebuilds].<br />
<br />
== Create a user account for KDE4 development ==<br />
<br />
{{Note|<br />
Some people like to have a separate user account for KDE 4 (for instance an old bug deleted files by mistake), and the instructions below were written with that approach.<br />
<br />
However it is much more efficient to do everything with a single user account, see [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br />
for more details. <br />
<br />
You can still follow the instructions below, but don't put the environment variables in your <tt>.bashrc</tt>, put them in a separate file that you source to switch to the KDE 4 environment.<br />
}}<br />
<br />
=== Option 1: Command Line ===<br />
<code bash><br />
useradd -m kde-devel<br />
passwd kde-devel<br />
</code><br />
<br />
=== Option 2: Using KControl ===<br />
<br />
Instead of using the commands above, you can also use the User module in the KDE Control Center if you already have KDE3 installed.<br />
<br />
=== Setting up the environment ===<br />
<br />
Copy the {{path|~/.bashrc}} from your normal user account to the new kde-devel account. Next, copy and paste the contents of the [[Getting Started/Increased Productivity in KDE4 with Scripts/.bashrc|example .bashrc]] into {{path|~kde-devel/.bashrc}}. Be sure to comment out the line <tt>alias make=makeobj</tt> if you do not have the <tt>[[Getting Started/Build/KDE4#Required Software|makeobj]]</tt> command available. You will probably also want to modify the path to make sure it doesn't include your kde3 paths. Also if you want to use KDevelop to develop KDE 4 applications you may pass the ''-GKDevelop3'' flag to the ''cmake'' command (to make CMake generate KDevelop project files, it will help to avoid rebuilding in the future, see [[Getting_Started/Set_up_KDE_4_for_development#Setting_up_the_environment|this]]). <br />
To make it run, you have to open a new bash or to execute <br />
<code bash><br />
source ~/.bashrc<br />
</code><br />
<br />
This will provide access to commands such as <tt>cmakekde</tt> that are used in this tutorial as well as ensure that the proper paths are in place for Qt, KDE and CMake binaries.<br />
<br />
For more information, please read the [[Getting Started/Increased Productivity in KDE4 with Scripts]] tutorial.<br />
<br />
=== Switching to the New User ===<br />
Switch to the user kde-devel: (don't forget the dash)<br />
<code bash><br />
su - kde-devel<br />
</code><br />
<br />
== The development user's shell ==<br />
<br />
On some systems a new user is configured by default to use {{path|/bin/sh}}. If this is not the case on your system, you can skip this section. Using {{path|/bin/sh}} can be very inconvenient to work with and you may want to change it to {{path|/bin/bash}} or another shell.<br />
On Ark Linux, you can skip this step - {{path|/bin/sh}} is {{path|bash}} on Ark Linux.<br />
<br />
=== Option 1: As the kde-devel user ===<br />
<br />
If you don't have root privileges and your system supports the changing of your own shell with the <tt>chsh</tt> application, then you could try to change your shell to {{path|/bin/bash}} by using:<br />
<code bash><br />
chsh -s /bin/bash kde-devel<br />
</code><br />
<br />
=== Option 2: As the root user ===<br />
<br />
If your system comes with the <tt>usermod</tt> application you can run the following command as root: <tt>usermod -s /bin/bash</tt>.<br />
<br />
Another option is to use the <tt>vipw</tt> application as root to safely edit your {{path|/etc/passwd}}. Locate 'kde-devel' in the the file. Change '{{path|/bin/sh}}' at the end of the line to read '{{path|/bin/bash}}', save your changes and exit.<br />
<br />
The new shell will be started automatically when you log in as the kde-devel user again.<br />
<br />
== D-Bus ==<br />
QtDBus and KDE are known to work with D-Bus versions 0.62, as well as 0.92 and upwards. Versions 0.60 and 0.61 may work too but are not tested. Versions 0.90 and 0.91 are known not to work. We recommend using post-1.0 release versions (at least 0.94), so consider upgrading if you haven't done so.<br />
<br />
You may skip this section if you have a recent D-Bus version or if you don't want to upgrade. You probably want to skip building the bindings until/unless you know you will be building HAL (see below).<br />
<br />
Before running these steps in the recipe, make sure your X11 headers and libraries are available. The configure script run on line 5 of the following instructions should output:<br />
Building X11 code: yes<br />
<br />
=== The Recipe ===<br />
<br />
{{tip|Make sure you did set up your environment correctly as described [[Getting_Started/Build/KDE4#Setting_up_the_environment|above]]. This is necessary for the <tt>cs</tt> and <tt>cb</tt> functions to work.}}<br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]] <br />
wget http://dbus.freedesktop.org/releases/dbus/dbus-1.0.2.tar.gz<br />
tar -xvzf dbus-1.0.2.tar.gz<br />
cd dbus-1.0.2/<br />
./configure --prefix=$DBUSDIR --localstatedir=/var<br />
make<br />
sudo make install<br />
sudo dbus-uuidgen --ensure<br />
<br />
# if you will be building HAL, you also need the glib bindings<br />
cs # see above<br />
wget http://dbus.freedesktop.org/releases/dbus-glib/dbus-glib-0.74.tar.gz<br />
tar -xvzf dbus-glib-0.74.tar.gz<br />
cd dbus-glib-0.74/<br />
./configure --prefix=$DBUSDIR<br />
make<br />
sudo make install<br />
<br />
=== What's Happening === <br />
After changing into the source directory (line 1), D-Bus source code is downloaded from freedesktop.org (line 2) and unpacked (line 3). After going into the newly created D-Bus directory (line 4), the build is set up using the supplied {{path|configure}} script (line 5). After building (line 6) and installing (line 7) D-Bus, we use the <tt>dbus-uuidgen</tt> tool to install a machine identification file that allows the bus to start automatically when the desktop session starts (line 8).<br />
<br />
Note that you need write access to {{path|/var}} for the last two steps. If your system does not have the sudo command, you can use the <tt>su</tt> command instead, e.g. <tt>su -c "make install"</tt>.<br />
<br />
The steps for building the glib bindings are similar to the above.<br />
<br />
== CMake ==<br />
Skip this if you have [http://cmake.org/ CMake] >=2.4.5 installed. <br />
You should be able to directly use the binary packages available on the [http://www.cmake.org/HTML/Download.html CMake site]. There are also distribution specific packages available.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click Here to learn more]] <br />
wget http://www.cmake.org/files/v2.4/cmake-2.4.6.tar.gz<br />
tar -zxf cmake-2.4.6.tar.gz<br />
mkdir cmake-build<br />
cd cmake-build <br />
../cmake-2.4.6/bootstrap<br />
make<br />
sudo make install<br />
<br />
=== What's Happening ===<br />
First, we go back to the <tt>kde-devel</tt> user's source directory (line 1), get the CMake sources (line 2) and unpack them (line 3). We create a directory to build CMake in (line 4) and go into it (line 5). We then run the CMake bootstrap script to set up the CMake build (line 6), then make (line 7) and install it (line 8) using the root user.<br />
<br />
If your system does not have the <tt>sudo</tt> command, you can instead do <tt>su -c "make install"</tt>.<br />
<br />
== Qt ==<br />
Next we need to get the Qt4 that is in KDE's source repository. KDE is guaranteed to build against any Qt 4.3. Qt 4.2 and earlier are not supported and will not work. You should use the copy in the KDE Subversion servers. (note: some distros, like Debian, tend to supply Qt with patches from KDE svn applied, so you may want to cheat and use precompiled Qt from your distro)<br />
<br />
=== The Recipe ===<br />
cd<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/qt-copy<br />
cd qt-copy<br />
./apply_patches<br />
./configure -qt-gif -no-exceptions -debug -fast \<br />
-prefix $QTDIR -nomake examples -nomake demos<br />
make -j2<br />
<br />
# if we don't install, we'll just clear obj files to<br />
# save disk space<br />
if [ $QTDIR = `pwd` ]; then \<br />
find . -name '*.o' -exec rm {} \; ; \<br />
else make install; fi;<br />
<br />
=== What's Happening ===<br />
We switch back to the <tt>kde-devel</tt> user's home directory (line 1) and download the source code using subversion (svn) from KDE's repository (line 2). After changing into the resulting {{path|qt-copy}} directory (line 3), we run a script that manages the patches that come with <tt>qt-copy</tt> (line 4). <br />
<br />
Once the patches have been applied, we then set up the build using the <tt>configure</tt> script (line 5-6). The various command line options used are explained in the {{path|qt-copy/README.qt-copy}} file. Finally, we build the minimal requirements for KDE (line 7) and install (line 10) Qt. If install dir is the same as the current dir (line 8), then we just free some space (line 9) instead. If you want all the example and demo applications, you can either build them individually or simply do a <tt>make</tt> from the {{path|qt-copy}} directory. <br />
<br />
Note that the installation does not require root as it installs Qt locally into {{path|$QTDIR}}. Anyway, installation is only needed if {{path|$QTDIR}} differs from {{path|$HOME/qt-copy}}, which is not the case if you have exactly followed the instructions.<br />
<br />
=== Troubleshooting ===<br />
If you get "error: X11/Xlib.h: No such file or directory", install the devel package of <tt>xorg</tt> (the actual name may vary between operating systems, for example it is <tt>xorg-dev</tt> on Ubuntu based systems such as Kubuntu). <br />
<br />
If you get an error in the configure step about missing defines, check the value of <tt>$QMAKESPEC</tt>. Some distributions set this to point directly to the system-installed Qt. If <tt>unset QMAKESPEC</tt> solves the problem, you probably want to add it to the <tt>~/.bashrc</tt> script.<br />
<br />
If you get an error ".pch/debug-shared/QtCore", this is because Qt-4.3 enables precompiled headers if your gcc supports it, but for some reason it doesn't work for you. If you use distcc, configure qt with -no-pch. If you use icecream, update to the latest icecream from svn trunk.<br />
<br />
Try running any Qt program, like {{program|assistant}}. '''Note:''' You may need to run <tt>xhost +local:kde-devel</tt> as your regular kde3 user to run this application. If it crashes in QSpanData::adjustSpanMethods, then your problem is the oxygen style. Try removing {{path|lib/kde4/plugins/styles/kstyle-oxygen.so}} and {{path|lib/kde4/plugins/styles/oxygen.so}} if they exist in the KDE install prefix.<br />
<br />
== HAL ==<br />
<br />
{{tip|You can use qdbusviewer to see if you have org.freedesktop.hal. If not, you might need a newer version of hal. If you have org.freedesktop.hal, you probably don't need to, and don't ''want'' to, roll your own HAL.}}<br />
<br />
If your system requires you to build a newer version of HAL, there's a decent chance you'll need to build other stuff as well, some of which may not be straight forward. Since this should only be required for older distros, instructions are on [[Getting_Started/Build/HAL| a separate page]].<br />
<br />
== kdesupport ==<br />
<br />
{{warning|If you have jumped to this section without reading [[Getting_Started/Build/KDE4#Setting_up_the_environment|Setting Up The Environment]], '''the recipes provided will not work'''. <br />
<br />
The recipes are not in error; <tt>cs</tt> and <tt>cb</tt> are not typos. Your environment '''needs''' to be set up correctly for these instructions to work for you.}}<br />
<br />
There are several libraries that KDE applications rely on in the kdesupport module. This includes Strigi and Soprano for file metadata and search, eigen for visual effects in applications such as Kalzium, taglib for music players and qca for some cryptographic needs. <br />
<br />
Strigi itself has a few dependencies as well: you will need the libraries and headers for libz, libbz2, openssl (libcrypto or libssl), libclucene (=0.9.16; version 0.9.17 does '''not''' work), and either libxml2 or libexpat.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/kdesupport/<br />
cd kdesupport<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1). We download the sources in kdesupport using subversion (line 2), go into the new {{path|~/kde/src/kdesupport}} directory (line 3), and commence the build (line 4). This will leave us in the kdesupport build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you get <br />
cmakekde: command not found<br />
then you have to go manualy into the kdesupport directory in ~ and execute the command cmakekde. if this still doesnt work, then something is wrong with your bashrc.<br />
<br />
If you get <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 />
LIBXML2_INCLUDE_DIR (ADVANCED)<br />
you should install the development package for libxml2.<br />
<br />
If you get <br />
CMake Error: Could NOT find REDLAND<br />
then you need librdf from the Redland.<br />
If your distribution does not provide the librdf package, you can download the source there: [http://download.librdf.org/source/ http://download.librdf.org/source/] and build it.<br />
(Gentoo users: The ebuild for librdf is named dev-libs/redland)<br />
<br />
If you get<br />
Fetching external item into 'kdesupport/admin'<br />
Error validating server certificate for 'https://...'<br />
see [http://techbase.kde.org/Getting_Started/Sources/Using_Subversion_with_KDE Using Subversion with KDE]<br />
<br />
If you get<br />
FILE cannot create directory: /usr/lib[64]/qt4/plugins/crypto. Maybe need administrative privileges.<br />
- - -<br />
make: *** [install] Error 255<br />
take a second look in the .bashrc file described above, are paths correct? Alternatively, you may see this error if you decided to use a distribution installed version of qt4 and skipped the Qt install above. Either install qt-copy as describe above, or "sudo make install".<br />
<br />
== kdelibs ==<br />
<br />
We can now move on to building KDE's base libraries.<br />
<br />
=== The Recipe ===<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
mkdir KDE && cd KDE<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdelibs<br />
cd kdelibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1) then make and go into the KDE directory (line 2). We download the sources for kdelibs using subversion (line 3), go into the new {{path|~/kde/src/KDE/kdelibs}} directory (line 4), and commence the build (line 5). This will leave us in the <tt>kdelibs</tt> build directory after the build is completed.<br />
<br />
{{tip|There might be missing dependencies on your system! They are easily overlooked in the output of <tt>cmakekde</tt>.<br />
You might want to do a <tt>cmake $KDE_SRC/KDE/MODULE_NAME</tt> prior to compiling any kde modules (like kdelibs, kdepimlibs etc.)}}<br />
<br />
=== Additional KDE-specific CMake modules ===<br />
There are additional CMake modules in {{path|kdelibs/cmake/modules/}} that are necessary for building KDE4 applications. These will be installed for you when kdelibs itself is installed.<br />
<br />
=== Troubleshooting ===<br />
If you have problems compiling kdelibs, first make sure the software in the [[Getting_Started/Build/KDE4#Required_Software|Required Software]] section above is installed and works. Other possible hints include:<br />
* If the <tt>cmakekde</tt> command fails stating that CMake requires an out of source build directory, remove {{path|~/kde/src/KDE/kdelibs/CMakeCache.txt}}, and try again.<br />
<br />
If <tt>cmakekde</tt> still gives the same error then try this <br />
cd<br />
cmake -DCMAKE_INSTALL_PREFIX=$KDEDIR \<br />
-DCMAKE_BUILD_TYPE=debugfull \<br />
-DKDE4_BUILD_TESTS=ON \<br />
~/kde/src/KDE/kdelibs<br />
make<br />
make install<br />
* If you received an error stating "Please create a separate build directory and run 'cmake path_to_kdelibs [options]' there.", then you need to change to your build directory before running cmakekde. (e.g <tt>cs KDE/kdelibs && cb && cmakekde</tt>) If the message stays, run 'svn status' in the kdelibs directory and remove all files labeled with '?'.<br />
* If Qt wasn't found or the wrong version of Qt was found, make sure that the qmake from the Qt you need is the first qmake in the path.<br />
* If the problems persist, try the CMake make-option <tt>--keep-going</tt>.<br />
* Here you need the libungif library, otherwise you will get an error message like "<tt>Could NOT find GIF</tt>".<br />
* Qt-4.3 upgrade: if you get a link error in kjsembed talking about QScriptEngine, edit CMakeCache.txt in kdelibs and remove the lines that talk about QT_QTUITOOLS_LIBRARY, then type make again (that static library has a new dependency, and the cmake code that adds it needs to run).<br />
* if you get <code>CMake Error: KDE Requires Qt to be built with SSL support<br />
</code>, install openssl-devel, remove CMakeCache.txt and re-compile QT.<br />
* if you get <code>kdelibs/kimgio/ico.cpp:188: undefined reference to `QImage::jumpTable()'</code> it means you compiled QT without QT3 support(no, linking to a true QT3 install won't work)<br />
<br />
== kdepimlibs ==<br />
After <tt>kdelibs</tt>, but before ''kdebase'', you need to build and install ''kdepimlibs''.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdepimlibs<br />
cd kdepimlibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We go into the KDE source directory (line 1), download the source code for kdepimlibs using subversion (line 2) and then go into the new {{path|~/kde/src/KDE/kdepimlibs}} directory (line 3). We then commence the build (line 4). This will leave us in the <tt>kdepimlibs</tt> build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you have trouble compiling kdepimlibs:<br />
* the cmakekde command may require a later version of the gpgme library. This is available from the project's web site: http://www.gnupg.org/(en)/download/index.html - please note that the build of gpgme also requires libgpg-error, also available from the same location. Both libraries are installed by the "./configure", "make" and "sudo make install" sequence, with the gpgme library configured with the additional "--with-gpg-error-prefix" parameter. You may need to overwrite your existing "/usr/bin/gpgme-config" file with the newer version for the kdepimlibs to pick up the new install.<br />
<br />
== kdebase ==<br />
kdebase is divided into three parts:<br />
* '''apps'''<br />
:This contains applications like Dolphin or KWrite.<br />
* '''runtime'''<br />
:This contains things needed by every application at runtime, like icons. It is a required dependency for each KDE application, so you have to compile and install this.<br />
* '''workspace'''<br />
:This contains things specific to the KDE desktop, like Plasma or the window manager. Most stuff here depends on X11. You only need it if you want to build a full KDE desktop.<br />
<br />
You can build all of kdebase at once, which is described in the recipe below. If you only want to build kdebase-runtime, which is the only requirement, you can replace <code bash>cd kdebase</code> with <code bash>cd kdebase/runtime</code> in the receipe below.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdebase<br />
cd kdebase<br />
cmakekde<br />
<br />
=== Troubleshooting ===<br />
If you have troubles compiling kdebase:<br />
* Make sure you have the <tt>libxss headers</tt> installed. (Usually you got undefined references on xscreensaver objects if you do not have those headers)<br />
* <tt>which meinproc</tt> has to deliver {{path|/home/kde-devel/kde/bin/meinproc}}<br />
* if cmakekde can not find the path of kdepimlibs, edit the file {{path|$KDE_BUILD/KDE/kdebase/CMakeCache.txt}} and manually set <tt>KDEPIMLIBS_INCLUDE_DIR:PATH=$KDE_BUILD/kdepimlibs</tt><br />
* if you get an error saying "Please set the following variables: X11_XTest_LIB (ADVANCED)", install the devel package of <tt>Xtst</tt>. On some systems, this is packaged separately from <tt>xext</tt> and called <tt>x11proto-xext-dev</tt> or <tt>libxtst-dev</tt>. You may also need to remove the CMakeCache.txt file in the build dir after installing the package.<br />
* the same for "X11_Xinerama_LIB (ADVANCED)" where you will need the devel package for <tt>xinerama</tt>.<br />
* if you get an error complaining about a missing variable X11_Xrandr_LIB, you need the devel package for libxrandr (libxrandr-devel on ubuntu-systems)<br />
* if you get the error "Please set the following variables: FONTCONFIG_INCLUDE_DIR, FONTCONFIG_LIBRARIES (ADVANCED)", then you need to install the libfontconfig headers<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: KMETADATA_LIBRARIES", you need to install soprano from kdesupport and to rebuild kdelibs<br />
* if you get the error "‘XserverRegion’ does not name a type" make sure you have libxcomposite headers installed (<tt>libxcomposite-dev</tt> in ubuntu)<br />
<br />
== Generating local API documentation ==<br />
Although the API documentation for KDE is available online at [http://api.kde.org api.kde.org], it is sometimes useful to have it on your own disk, for example when you want to use [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|KDevelop]] for browsing the documentation or when you are not able to be online all the time.<br />
<br />
Be aware that generating the API documentation can take several hours and takes almost half a gigabyte of diskspace.<br />
The generation is handled by a script in {{path|kdelibs/doc/api}}, you need <tt>doxygen</tt> to be able to run it. <br />
<br />
To build the API documentation for kdelibs, type the following:<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE/kdelibs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Repeat for other modules as desired.<br><br />
cd <module home><br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Another, even easier method involves downloading this [[Doxyfile]] to your local system. Then simply change directory to where you want to create the documentation and run<br />
<code bash><br />
% doxygen /path/to/Doxyfile<br />
</code><br />
Then review the file {{path|doxygen.log}} to see the doxygen errors and warnings. You'll find the actual documentation in the {{path|apidocs}} subdirectory.<br />
<br />
== Staying up to date ==<br />
<br />
In order to keep the kde4 installation up to date, each of the modules installed should be updated periodically. As Monday is the day for big changes in kdelibs, Tuesday may be the best day to do this. For each module checked out, run <tt>svn up</tt> and <tt>make</tt>.<br />
<br />
For example:<br />
<code bash><br />
cs kdesupport # cs is not a typo<br />
svn up<br />
cb # cb is not a typo<br />
make -j2 VERBOSE=1 && make install<br />
</code><br />
<br />
== General troubleshooting ==<br />
<br />
What can happen over time, after some <tt>svn up</tt> commands, is that some of the tools used in the KDE build chain change their output format. For example, <tt>kcfg</tt> files are read by <tt>kconfig_compiler</tt> to produce configuration dialogs. CMake cannot detect those changes, and the compilation might fail. A workaround is to always force a re-generation of all such files:<br />
find $KDE_SRC/KDE/kdebase -name "*.kcfg" | xargs touch<br />
The same applies to <tt>ui</tt> files as produced by Qt designer.<br />
<br />
== Success! ==<br />
<br />
You are now ready to start building other svn modules in the same fashion as you built kdebase, running and testing KDE4 or writing your own patches and applications.<br />
<br />
See the [[Getting Started/Set up KDE 4 for development|Set up KDE 4 for development]] tutorial for how to start KDE 4 applications and how to use KDevelop to work on them.<br />
<br />
[[Category:Build KDE]]<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Getting_Started/Build/KDE4&diff=13231Getting Started/Build/KDE42007-08-27T11:16:59Z<p>Powerfox: /* Setting up the environment */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Getting_Started/Build/KDE4}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Getting Started|<br />
<br />
name=Building KDE4 From Source|<br />
<br />
pre=[[../../Sources/Anonymous_SVN|Anonymous SVN Quickstart Guide]]|<br />
<br />
next=[[../../Set_up_KDE_4_for_development|Set up KDE 4 for development]]|<br />
<br />
reading=[http://kdesvn-build.kde.org/ kdesvn-build: The KDE From Subversion Build Tool]<br>[[../../Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br>[[Development/Tutorials/CMake |Introduction to CMake]]<br>[[../KDE4/FreeBSD|FreeBSD notes]]<br>[[../KDE4/Mac OS X|Instructions for Mac OS X]]<br>[[../KDE4/Windows|Instructions for MS Windows]]|<br />
}}<br />
<br />
== Abstract ==<br />
<br />
This tutorial shows one way to get KDE from trunk running on Linux/BSD systems. There are also tutorials for [[/FreeBSD|FreeBSD]], [http://www.kdelibs.com/ Windows], [[/Mac OS X|Mac OS X]] and [http://solaris.kde.org/ Solaris]. Throughout the tutorial the bash shell is used.<br />
<br />
{{warning|Expect a higher risk of build failure '''on Mondays''' when most kdelibs changes are committed. [http://developer.kde.org/~dirk/dashboard/ Dashboard] reports unexpected breakages. You are encouraged to fix failing modules.<br />
}}<br />
<br />
== Required Software ==<br />
<br />
The following must be installed first before you can successfully complete this tutorial:<br />
* gcc and g++ from the gcc project, preferably version 4.1 or higher<br />
* svn, the subversion revision control client<br />
* pkg-config<br />
* development libraries and headers for X11, OpenGL (mesa-common-dev and libglu1-mesa-dev), libjpeg, libpng, libungif, [http://clucene.sourceforge.net/index.php/Downloads libclucene], [http://download.librdf.org/source/ librdf], libxml2 and libxslt<br />
* the <tt>makeobj</tt> script, which is part of kdesdk. You can install it as part of kdesdk (kdesdk-scripts on Debian) or similar package, or just download it itself from [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/makeobj WebSVN]<br />
* the [http://freedesktop.org/wiki/Software/shared-mime-info shared-mime-info package], which is the freedesktop MIME standard KDE is using now<br />
* [http://boost.org/ boost], needed by kdebase; after compiling and/or installing boost, in order to make cmake aware about its location (FindBoost), add boost directory (the one containing include subdirectory) to CMAKE_INCLUDE_PATH or set an environment variable called BOOST_ROOT pointing to boost directory.<br />
<br />
=== Ark Linux ===<br />
In Ark Linux, the build dependencies you need are installed with:<br />
<br />
<code bash><br />
apt-get install devel-core libxml-devel libxslt-devel bzip2-devel \<br />
clucene-devel librdf-devel shared-mime-info xorg-Mesa-libGL-devel \<br />
subversion boost-devel doxygen giflib-devel dbus-devel openssl-devel \<br />
alsa-lib-devel kdesdk-scripts qt4-devel<br />
</code><br />
<br />
If you prefer a graphical interface, select the packages listed above in the "Install Software" tool in Mission Control.<br />
<br />
This includes installation of CMake, DBus and Qt - you can skip steps 5, 6 and 7.<br />
<br />
=== Kubuntu ===<br />
<br />
In Kubuntu 7.04 (Feisty) the build dependencies you need are installed with:<br />
<code bash><br />
sudo aptitude install build-essential cdbs debhelper cmake \<br />
libxml2-dev libxslt1-dev libbz2-dev libclucene-dev librdf-dev \<br />
shared-mime-info libgl1-mesa-dev libglu1-mesa-dev mesa-common-dev \<br />
libxext-dev libjpeg-dev libpng-dev subversion libsm-dev libxinerama-dev \<br />
libxrender-dev libfontconfig-dev libboost-dev libxcursor-dev doxygen \<br />
libungif4-dev libdbus-1-dev libgpgme11-dev libssl-dev libgpgme11-dev \<br />
libasound2-dev kdesdk-scripts<br />
</code><br />
<br />
You can skip the manual installation of CMake 2.4.6 and DBus with: <br />
<code bash><br />
sudo aptitude install libdbus-1-dev cmake<br />
</code><br />
<br />
For a fully functional API documentation framework you also need:<br />
<code bash><br />
sudo aptitude install graphviz<br />
</code><br />
<br />
=== openSUSE ===<br />
<br />
In openSUSE 10.2 and newer, you can install packages using [http://en.opensuse.org/Zypper Zypper]:<br />
<code bash><br />
sudo zypper install <package-name><br />
</code><br />
<br />
In older releases of SUSE, you can use YaST:<br />
<code bash><br />
su<br />
yast -i <packagename><br />
</code><br />
<br />
'''Required Packages'''<br />
<br />
The packages you will need to install are:<br />
<code><br />
xorg-x11-devel<br />
libxml2-devel <br />
kdesdk3 <br />
clucene-core-devel <br />
boost-devel<br />
libjpeg-devel <br />
liblrdf-devel <br />
libpng-devel <br />
libxslt-devel <br />
libredland-devel<br />
Mesa-devel <br />
giflib-devel <br />
subversion <br />
gcc <br />
gcc-c++<br />
</code><br />
<br />
'''Optional Packages'''<br />
<br />
You can skip the manual installation of Qt 4.3, CMake 2.4.6 and DBus by installing the adding the openSUSE Build Service KDE4 Repository to your installation sources.<br />
<br />
For openSUSE 10.2 and newer do:<br />
<code><br />
sudo zypper service-add http://software.opensuse.org/download/KDE:/KDE4/openSUSE_10.2 KDE4-102<br />
</code><br />
<br />
For older versions of SUSE Linux do:<br />
<code><br />
su<br />
installation_sources -a http://software.opensuse.org/download/KDE:/KDE4/[YOUR SUSE LINUX VERSION]<br />
</code><br />
<br />
Now install the following packages (and their dependencies):<br />
<code><br />
cmake<br />
dbus-1-devel<br />
libqt4-devel<br />
</code><br />
<br />
And for fully functional apidox framework you also need:<br />
<code><br />
graphviz<br />
</code><br />
<br />
CMake binary packages for openSUSE are available from [http://software.opensuse.org/download/devel:/tools:/building/ openSUSE build service].<br />
<br />
=== Gentoo ===<br />
<br />
==== Install by hand ====<br />
<br />
You can use most stable ebuilds just remember to sync your portage before you begin.<br />
<br />
We need to be unmasked and/or kept at a lower version to continue.<br />
<br />
<code bash><br />
# echo 'x11-libs/qt' >> /etc/portage/package.unmask<br />
# echo 'dev-util/cmake' >> /etc/portage/package.unmask<br />
# echo 'dev-cpp/clucene' >> /etc/portage/package.unmask<br />
# echo '>dev-cpp/clucene-0.9.16a' >> /etc/portage/package.mask<br />
</code><br />
<br />
Make sure you have set the berkdb USE flag for redland, otherwise nepomuk won't work:<br />
<br />
<code bash><br />
# echo 'dev-libs/redland berkdb' >> /etc/portage/package.use<br />
</code><br />
<br />
<br />
These are the packages you will need to install, some may already be installed so you may skip those by adding the update flag to emerge.<br />
<br />
<code bash><br />
$ emerge -avu ebuild/name<br />
</code><br />
<br />
sys-devel/gcc<br />
dev-util/subversion<br />
dev-util/pkgconfig<br />
x11-base/xorg-x11<br />
media-libs/glut<br />
media-libs/mesa<br />
media-libs/jpeg<br />
media-libs/libpng<br />
media-libs/giflib<br />
dev-cpp/clucene<br />
dev-util/cppunit<br />
media-libs/liblrdf<br />
dev-libs/libxml2<br />
dev-libs/libxslt<br />
x11-misc/shared-mime-info<br />
kde-base/kdesdk-scripts<br />
dev-libs/boost<br />
x11-libs/qt<br />
dev-util/cmake<br />
sys-apps/dbus<br />
dev-libs/redland<br />
<br />
Provided you have emerged these ebuilds, you can skip compiling them by hand and proceed to [[Getting_Started/Build/KDE4#kdesupport|kdesupport section]].<br />
<br />
Good luck!<br />
<br />
==== Install via portage ====<br />
<br />
Also you can install the KDE 4 packages directly via <br />
<code bash><br />
emerge -a <packagename><br />
</code><br />
<br />
To get the things you need, [http://gentoo-wiki.com/TIP_Overlays#Layman install layman] and then pull in the KDE overlay (which contains experimental KDE ebuilds): <br />
<code bash><br />
layman -a kde<br />
</code><br />
After this you need to adjust some USE-flags for KDE 4 and tell portage to use the testing KDE 4 ebuilds instead of the stable KDE 3 ones. <br />
<br />
That way portage will do the dependency tracking for you. <br />
<br />
Detailed instructions on building KDE 4 in Gentoo via portage can be found in the [http://overlays.gentoo.org/proj/kde/wiki KDE overlay wiki]. They are discussed in the thread [http://forums.gentoo.org/viewtopic-t-530111-postdays-0-postorder-asc-start-0.html KDE 4 monolithic ebuilds].<br />
<br />
== Create a user account for KDE4 development ==<br />
<br />
{{Note|<br />
Some people like to have a separate user account for KDE 4 (for instance an old bug deleted files by mistake), and the instructions below were written with that approach.<br />
<br />
However it is much more efficient to do everything with a single user account, see [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts|Increased Productivity in KDE4 with Scripts]]<br />
for more details. <br />
<br />
You can still follow the instructions below, but don't put the environment variables in your <tt>.bashrc</tt>, put them in a separate file that you source to switch to the KDE 4 environment.<br />
}}<br />
<br />
=== Option 1: Command Line ===<br />
<code bash><br />
useradd -m kde-devel<br />
passwd kde-devel<br />
</code><br />
<br />
=== Option 2: Using KControl ===<br />
<br />
Instead of using the commands above, you can also use the User module in the KDE Control Center if you already have KDE3 installed.<br />
<br />
=== Setting up the environment ===<br />
<br />
Copy the {{path|~/.bashrc}} from your normal user account to the new kde-devel account. Next, copy and paste the contents of the [[Getting Started/Increased Productivity in KDE4 with Scripts/.bashrc|example .bashrc]] into {{path|~kde-devel/.bashrc}}. Be sure to comment out the line <tt>alias make=makeobj</tt> if you do not have the <tt>[[Getting Started/Build/KDE4#Required Software|makeobj]]</tt> command available. You will probably also want to modify the path to make sure it doesn't include your kde3 paths. Also if you want to use KDevelop to develop KDE 4 applications you may pass the ''-GKDevelop3'' flag to the ''cmake'' command (to make CMake generate KDevelop project files, see [[Getting_Started/Set_up_KDE_4_for_development#Setting_up_the_environment|this]]. <br />
To make it run, you have to open a new bash or to execute <br />
<code bash><br />
source ~/.bashrc<br />
</code><br />
<br />
This will provide access to commands such as <tt>cmakekde</tt> that are used in this tutorial as well as ensure that the proper paths are in place for Qt, KDE and CMake binaries.<br />
<br />
For more information, please read the [[Getting Started/Increased Productivity in KDE4 with Scripts]] tutorial.<br />
<br />
=== Switching to the New User ===<br />
Switch to the user kde-devel: (don't forget the dash)<br />
<code bash><br />
su - kde-devel<br />
</code><br />
<br />
== The development user's shell ==<br />
<br />
On some systems a new user is configured by default to use {{path|/bin/sh}}. If this is not the case on your system, you can skip this section. Using {{path|/bin/sh}} can be very inconvenient to work with and you may want to change it to {{path|/bin/bash}} or another shell.<br />
On Ark Linux, you can skip this step - {{path|/bin/sh}} is {{path|bash}} on Ark Linux.<br />
<br />
=== Option 1: As the kde-devel user ===<br />
<br />
If you don't have root privileges and your system supports the changing of your own shell with the <tt>chsh</tt> application, then you could try to change your shell to {{path|/bin/bash}} by using:<br />
<code bash><br />
chsh -s /bin/bash kde-devel<br />
</code><br />
<br />
=== Option 2: As the root user ===<br />
<br />
If your system comes with the <tt>usermod</tt> application you can run the following command as root: <tt>usermod -s /bin/bash</tt>.<br />
<br />
Another option is to use the <tt>vipw</tt> application as root to safely edit your {{path|/etc/passwd}}. Locate 'kde-devel' in the the file. Change '{{path|/bin/sh}}' at the end of the line to read '{{path|/bin/bash}}', save your changes and exit.<br />
<br />
The new shell will be started automatically when you log in as the kde-devel user again.<br />
<br />
== D-Bus ==<br />
QtDBus and KDE are known to work with D-Bus versions 0.62, as well as 0.92 and upwards. Versions 0.60 and 0.61 may work too but are not tested. Versions 0.90 and 0.91 are known not to work. We recommend using post-1.0 release versions (at least 0.94), so consider upgrading if you haven't done so.<br />
<br />
You may skip this section if you have a recent D-Bus version or if you don't want to upgrade. You probably want to skip building the bindings until/unless you know you will be building HAL (see below).<br />
<br />
Before running these steps in the recipe, make sure your X11 headers and libraries are available. The configure script run on line 5 of the following instructions should output:<br />
Building X11 code: yes<br />
<br />
=== The Recipe ===<br />
<br />
{{tip|Make sure you did set up your environment correctly as described [[Getting_Started/Build/KDE4#Setting_up_the_environment|above]]. This is necessary for the <tt>cs</tt> and <tt>cb</tt> functions to work.}}<br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click here to learn more]] <br />
wget http://dbus.freedesktop.org/releases/dbus/dbus-1.0.2.tar.gz<br />
tar -xvzf dbus-1.0.2.tar.gz<br />
cd dbus-1.0.2/<br />
./configure --prefix=$DBUSDIR --localstatedir=/var<br />
make<br />
sudo make install<br />
sudo dbus-uuidgen --ensure<br />
<br />
# if you will be building HAL, you also need the glib bindings<br />
cs # see above<br />
wget http://dbus.freedesktop.org/releases/dbus-glib/dbus-glib-0.74.tar.gz<br />
tar -xvzf dbus-glib-0.74.tar.gz<br />
cd dbus-glib-0.74/<br />
./configure --prefix=$DBUSDIR<br />
make<br />
sudo make install<br />
<br />
=== What's Happening === <br />
After changing into the source directory (line 1), D-Bus source code is downloaded from freedesktop.org (line 2) and unpacked (line 3). After going into the newly created D-Bus directory (line 4), the build is set up using the supplied {{path|configure}} script (line 5). After building (line 6) and installing (line 7) D-Bus, we use the <tt>dbus-uuidgen</tt> tool to install a machine identification file that allows the bus to start automatically when the desktop session starts (line 8).<br />
<br />
Note that you need write access to {{path|/var}} for the last two steps. If your system does not have the sudo command, you can use the <tt>su</tt> command instead, e.g. <tt>su -c "make install"</tt>.<br />
<br />
The steps for building the glib bindings are similar to the above.<br />
<br />
== CMake ==<br />
Skip this if you have [http://cmake.org/ CMake] >=2.4.5 installed. <br />
You should be able to directly use the binary packages available on the [http://www.cmake.org/HTML/Download.html CMake site]. There are also distribution specific packages available.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|'cs' is a bash function, click Here to learn more]] <br />
wget http://www.cmake.org/files/v2.4/cmake-2.4.6.tar.gz<br />
tar -zxf cmake-2.4.6.tar.gz<br />
mkdir cmake-build<br />
cd cmake-build <br />
../cmake-2.4.6/bootstrap<br />
make<br />
sudo make install<br />
<br />
=== What's Happening ===<br />
First, we go back to the <tt>kde-devel</tt> user's source directory (line 1), get the CMake sources (line 2) and unpack them (line 3). We create a directory to build CMake in (line 4) and go into it (line 5). We then run the CMake bootstrap script to set up the CMake build (line 6), then make (line 7) and install it (line 8) using the root user.<br />
<br />
If your system does not have the <tt>sudo</tt> command, you can instead do <tt>su -c "make install"</tt>.<br />
<br />
== Qt ==<br />
Next we need to get the Qt4 that is in KDE's source repository. KDE is guaranteed to build against any Qt 4.3. Qt 4.2 and earlier are not supported and will not work. You should use the copy in the KDE Subversion servers. (note: some distros, like Debian, tend to supply Qt with patches from KDE svn applied, so you may want to cheat and use precompiled Qt from your distro)<br />
<br />
=== The Recipe ===<br />
cd<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/qt-copy<br />
cd qt-copy<br />
./apply_patches<br />
./configure -qt-gif -no-exceptions -debug -fast \<br />
-prefix $QTDIR -nomake examples -nomake demos<br />
make -j2<br />
<br />
# if we don't install, we'll just clear obj files to<br />
# save disk space<br />
if [ $QTDIR = `pwd` ]; then \<br />
find . -name '*.o' -exec rm {} \; ; \<br />
else make install; fi;<br />
<br />
=== What's Happening ===<br />
We switch back to the <tt>kde-devel</tt> user's home directory (line 1) and download the source code using subversion (svn) from KDE's repository (line 2). After changing into the resulting {{path|qt-copy}} directory (line 3), we run a script that manages the patches that come with <tt>qt-copy</tt> (line 4). <br />
<br />
Once the patches have been applied, we then set up the build using the <tt>configure</tt> script (line 5-6). The various command line options used are explained in the {{path|qt-copy/README.qt-copy}} file. Finally, we build the minimal requirements for KDE (line 7) and install (line 10) Qt. If install dir is the same as the current dir (line 8), then we just free some space (line 9) instead. If you want all the example and demo applications, you can either build them individually or simply do a <tt>make</tt> from the {{path|qt-copy}} directory. <br />
<br />
Note that the installation does not require root as it installs Qt locally into {{path|$QTDIR}}. Anyway, installation is only needed if {{path|$QTDIR}} differs from {{path|$HOME/qt-copy}}, which is not the case if you have exactly followed the instructions.<br />
<br />
=== Troubleshooting ===<br />
If you get "error: X11/Xlib.h: No such file or directory", install the devel package of <tt>xorg</tt> (the actual name may vary between operating systems, for example it is <tt>xorg-dev</tt> on Ubuntu based systems such as Kubuntu). <br />
<br />
If you get an error in the configure step about missing defines, check the value of <tt>$QMAKESPEC</tt>. Some distributions set this to point directly to the system-installed Qt. If <tt>unset QMAKESPEC</tt> solves the problem, you probably want to add it to the <tt>~/.bashrc</tt> script.<br />
<br />
If you get an error ".pch/debug-shared/QtCore", this is because Qt-4.3 enables precompiled headers if your gcc supports it, but for some reason it doesn't work for you. If you use distcc, configure qt with -no-pch. If you use icecream, update to the latest icecream from svn trunk.<br />
<br />
Try running any Qt program, like {{program|assistant}}. '''Note:''' You may need to run <tt>xhost +local:kde-devel</tt> as your regular kde3 user to run this application. If it crashes in QSpanData::adjustSpanMethods, then your problem is the oxygen style. Try removing {{path|lib/kde4/plugins/styles/kstyle-oxygen.so}} and {{path|lib/kde4/plugins/styles/oxygen.so}} if they exist in the KDE install prefix.<br />
<br />
== HAL ==<br />
<br />
{{tip|You can use qdbusviewer to see if you have org.freedesktop.hal. If not, you might need a newer version of hal. If you have org.freedesktop.hal, you probably don't need to, and don't ''want'' to, roll your own HAL.}}<br />
<br />
If your system requires you to build a newer version of HAL, there's a decent chance you'll need to build other stuff as well, some of which may not be straight forward. Since this should only be required for older distros, instructions are on [[Getting_Started/Build/HAL| a separate page]].<br />
<br />
== kdesupport ==<br />
<br />
{{warning|If you have jumped to this section without reading [[Getting_Started/Build/KDE4#Setting_up_the_environment|Setting Up The Environment]], '''the recipes provided will not work'''. <br />
<br />
The recipes are not in error; <tt>cs</tt> and <tt>cb</tt> are not typos. Your environment '''needs''' to be set up correctly for these instructions to work for you.}}<br />
<br />
There are several libraries that KDE applications rely on in the kdesupport module. This includes Strigi and Soprano for file metadata and search, eigen for visual effects in applications such as Kalzium, taglib for music players and qca for some cryptographic needs. <br />
<br />
Strigi itself has a few dependencies as well: you will need the libraries and headers for libz, libbz2, openssl (libcrypto or libssl), libclucene (=0.9.16; version 0.9.17 does '''not''' work), and either libxml2 or libexpat.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/kdesupport/<br />
cd kdesupport<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1). We download the sources in kdesupport using subversion (line 2), go into the new {{path|~/kde/src/kdesupport}} directory (line 3), and commence the build (line 4). This will leave us in the kdesupport build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you get <br />
cmakekde: command not found<br />
then you have to go manualy into the kdesupport directory in ~ and execute the command cmakekde. if this still doesnt work, then something is wrong with your bashrc.<br />
<br />
If you get <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 />
LIBXML2_INCLUDE_DIR (ADVANCED)<br />
you should install the development package for libxml2.<br />
<br />
If you get <br />
CMake Error: Could NOT find REDLAND<br />
then you need librdf from the Redland.<br />
If your distribution does not provide the librdf package, you can download the source there: [http://download.librdf.org/source/ http://download.librdf.org/source/] and build it.<br />
(Gentoo users: The ebuild for librdf is named dev-libs/redland)<br />
<br />
If you get<br />
Fetching external item into 'kdesupport/admin'<br />
Error validating server certificate for 'https://...'<br />
see [http://techbase.kde.org/Getting_Started/Sources/Using_Subversion_with_KDE Using Subversion with KDE]<br />
<br />
If you get<br />
FILE cannot create directory: /usr/lib[64]/qt4/plugins/crypto. Maybe need administrative privileges.<br />
- - -<br />
make: *** [install] Error 255<br />
take a second look in the .bashrc file described above, are paths correct? Alternatively, you may see this error if you decided to use a distribution installed version of qt4 and skipped the Qt install above. Either install qt-copy as describe above, or "sudo make install".<br />
<br />
== kdelibs ==<br />
<br />
We can now move on to building KDE's base libraries.<br />
<br />
=== The Recipe ===<br />
cs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
mkdir KDE && cd KDE<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdelibs<br />
cd kdelibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We change to the base source directory (line 1) then make and go into the KDE directory (line 2). We download the sources for kdelibs using subversion (line 3), go into the new {{path|~/kde/src/KDE/kdelibs}} directory (line 4), and commence the build (line 5). This will leave us in the <tt>kdelibs</tt> build directory after the build is completed.<br />
<br />
{{tip|There might be missing dependencies on your system! They are easily overlooked in the output of <tt>cmakekde</tt>.<br />
You might want to do a <tt>cmake $KDE_SRC/KDE/MODULE_NAME</tt> prior to compiling any kde modules (like kdelibs, kdepimlibs etc.)}}<br />
<br />
=== Additional KDE-specific CMake modules ===<br />
There are additional CMake modules in {{path|kdelibs/cmake/modules/}} that are necessary for building KDE4 applications. These will be installed for you when kdelibs itself is installed.<br />
<br />
=== Troubleshooting ===<br />
If you have problems compiling kdelibs, first make sure the software in the [[Getting_Started/Build/KDE4#Required_Software|Required Software]] section above is installed and works. Other possible hints include:<br />
* If the <tt>cmakekde</tt> command fails stating that CMake requires an out of source build directory, remove {{path|~/kde/src/KDE/kdelibs/CMakeCache.txt}}, and try again.<br />
<br />
If <tt>cmakekde</tt> still gives the same error then try this <br />
cd<br />
cmake -DCMAKE_INSTALL_PREFIX=$KDEDIR \<br />
-DCMAKE_BUILD_TYPE=debugfull \<br />
-DKDE4_BUILD_TESTS=ON \<br />
~/kde/src/KDE/kdelibs<br />
make<br />
make install<br />
* If you received an error stating "Please create a separate build directory and run 'cmake path_to_kdelibs [options]' there.", then you need to change to your build directory before running cmakekde. (e.g <tt>cs KDE/kdelibs && cb && cmakekde</tt>) If the message stays, run 'svn status' in the kdelibs directory and remove all files labeled with '?'.<br />
* If Qt wasn't found or the wrong version of Qt was found, make sure that the qmake from the Qt you need is the first qmake in the path.<br />
* If the problems persist, try the CMake make-option <tt>--keep-going</tt>.<br />
* Here you need the libungif library, otherwise you will get an error message like "<tt>Could NOT find GIF</tt>".<br />
* Qt-4.3 upgrade: if you get a link error in kjsembed talking about QScriptEngine, edit CMakeCache.txt in kdelibs and remove the lines that talk about QT_QTUITOOLS_LIBRARY, then type make again (that static library has a new dependency, and the cmake code that adds it needs to run).<br />
* if you get <code>CMake Error: KDE Requires Qt to be built with SSL support<br />
</code>, install openssl-devel, remove CMakeCache.txt and re-compile QT.<br />
* if you get <code>kdelibs/kimgio/ico.cpp:188: undefined reference to `QImage::jumpTable()'</code> it means you compiled QT without QT3 support(no, linking to a true QT3 install won't work)<br />
<br />
== kdepimlibs ==<br />
After <tt>kdelibs</tt>, but before ''kdebase'', you need to build and install ''kdepimlibs''.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdepimlibs<br />
cd kdepimlibs<br />
cmakekde<br />
<br />
=== What's Happening ===<br />
We go into the KDE source directory (line 1), download the source code for kdepimlibs using subversion (line 2) and then go into the new {{path|~/kde/src/KDE/kdepimlibs}} directory (line 3). We then commence the build (line 4). This will leave us in the <tt>kdepimlibs</tt> build directory after the build is completed.<br />
<br />
=== Troubleshooting ===<br />
If you have trouble compiling kdepimlibs:<br />
* the cmakekde command may require a later version of the gpgme library. This is available from the project's web site: http://www.gnupg.org/(en)/download/index.html - please note that the build of gpgme also requires libgpg-error, also available from the same location. Both libraries are installed by the "./configure", "make" and "sudo make install" sequence, with the gpgme library configured with the additional "--with-gpg-error-prefix" parameter. You may need to overwrite your existing "/usr/bin/gpgme-config" file with the newer version for the kdepimlibs to pick up the new install.<br />
<br />
== kdebase ==<br />
kdebase is divided into three parts:<br />
* '''apps'''<br />
:This contains applications like Dolphin or KWrite.<br />
* '''runtime'''<br />
:This contains things needed by every application at runtime, like icons. It is a required dependency for each KDE application, so you have to compile and install this.<br />
* '''workspace'''<br />
:This contains things specific to the KDE desktop, like Plasma or the window manager. Most stuff here depends on X11. You only need it if you want to build a full KDE desktop.<br />
<br />
You can build all of kdebase at once, which is described in the recipe below. If you only want to build kdebase-runtime, which is the only requirement, you can replace <code bash>cd kdebase</code> with <code bash>cd kdebase/runtime</code> in the receipe below.<br />
<br />
=== The Recipe ===<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
svn checkout svn://anonsvn.kde.org/home/kde/trunk/KDE/kdebase<br />
cd kdebase<br />
cmakekde<br />
<br />
=== Troubleshooting ===<br />
If you have troubles compiling kdebase:<br />
* Make sure you have the <tt>libxss headers</tt> installed. (Usually you got undefined references on xscreensaver objects if you do not have those headers)<br />
* <tt>which meinproc</tt> has to deliver {{path|/home/kde-devel/kde/bin/meinproc}}<br />
* if cmakekde can not find the path of kdepimlibs, edit the file {{path|$KDE_BUILD/KDE/kdebase/CMakeCache.txt}} and manually set <tt>KDEPIMLIBS_INCLUDE_DIR:PATH=$KDE_BUILD/kdepimlibs</tt><br />
* if you get an error saying "Please set the following variables: X11_XTest_LIB (ADVANCED)", install the devel package of <tt>Xtst</tt>. On some systems, this is packaged separately from <tt>xext</tt> and called <tt>x11proto-xext-dev</tt> or <tt>libxtst-dev</tt>. You may also need to remove the CMakeCache.txt file in the build dir after installing the package.<br />
* the same for "X11_Xinerama_LIB (ADVANCED)" where you will need the devel package for <tt>xinerama</tt>.<br />
* if you get an error complaining about a missing variable X11_Xrandr_LIB, you need the devel package for libxrandr (libxrandr-devel on ubuntu-systems)<br />
* if you get the error "Please set the following variables: FONTCONFIG_INCLUDE_DIR, FONTCONFIG_LIBRARIES (ADVANCED)", then you need to install the libfontconfig headers<br />
* if you get the error "CMake Error: This project requires some variables to be set, and cmake can not find them. Please set the following variables: KMETADATA_LIBRARIES", you need to install soprano from kdesupport and to rebuild kdelibs<br />
* if you get the error "‘XserverRegion’ does not name a type" make sure you have libxcomposite headers installed (<tt>libxcomposite-dev</tt> in ubuntu)<br />
<br />
== Generating local API documentation ==<br />
Although the API documentation for KDE is available online at [http://api.kde.org api.kde.org], it is sometimes useful to have it on your own disk, for example when you want to use [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|KDevelop]] for browsing the documentation or when you are not able to be online all the time.<br />
<br />
Be aware that generating the API documentation can take several hours and takes almost half a gigabyte of diskspace.<br />
The generation is handled by a script in {{path|kdelibs/doc/api}}, you need <tt>doxygen</tt> to be able to run it. <br />
<br />
To build the API documentation for kdelibs, type the following:<br />
<!--'cs' and 'cb' are NOT typos!--><br />
cs KDE/kdelibs # [[Getting_Started/Increased_Productivity_in_KDE4_with_Scripts/.bashrc|cs is not a typo]]<br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Repeat for other modules as desired.<br><br />
cd <module home><br />
$KDE_SRC/KDE/kdelibs/doc/api/doxygen.sh \<br />
--doxdatadir=$KDE_SRC/KDE/kdelibs/doc/common .<br />
<br />
Another, even easier method involves downloading this [[Doxyfile]] to your local system. Then simply change directory to where you want to create the documentation and run<br />
<code bash><br />
% doxygen /path/to/Doxyfile<br />
</code><br />
Then review the file {{path|doxygen.log}} to see the doxygen errors and warnings. You'll find the actual documentation in the {{path|apidocs}} subdirectory.<br />
<br />
== Staying up to date ==<br />
<br />
In order to keep the kde4 installation up to date, each of the modules installed should be updated periodically. As Monday is the day for big changes in kdelibs, Tuesday may be the best day to do this. For each module checked out, run <tt>svn up</tt> and <tt>make</tt>.<br />
<br />
For example:<br />
<code bash><br />
cs kdesupport # cs is not a typo<br />
svn up<br />
cb # cb is not a typo<br />
make -j2 VERBOSE=1 && make install<br />
</code><br />
<br />
== General troubleshooting ==<br />
<br />
What can happen over time, after some <tt>svn up</tt> commands, is that some of the tools used in the KDE build chain change their output format. For example, <tt>kcfg</tt> files are read by <tt>kconfig_compiler</tt> to produce configuration dialogs. CMake cannot detect those changes, and the compilation might fail. A workaround is to always force a re-generation of all such files:<br />
find $KDE_SRC/KDE/kdebase -name "*.kcfg" | xargs touch<br />
The same applies to <tt>ui</tt> files as produced by Qt designer.<br />
<br />
== Success! ==<br />
<br />
You are now ready to start building other svn modules in the same fashion as you built kdebase, running and testing KDE4 or writing your own patches and applications.<br />
<br />
See the [[Getting Started/Set up KDE 4 for development|Set up KDE 4 for development]] tutorial for how to start KDE 4 applications and how to use KDevelop to work on them.<br />
<br />
[[Category:Build KDE]]<br />
[[Category:KDE4]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=13215Development/Tutorials/Using KActions (ru)2007-08-23T16:14:00Z<p>Powerfox: Updates</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Действия -- центральная концепция при реализации интерактивности программы.<br />
<br />
Например, нужно чтобы по нажатию кнопки на панели инструментов, комбинации клавиш или по выбору некоторого пункта меню очищалось текстовое поле. Всё это можно сделать с помощью одного действия {{class|KAction}}.<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Для создания действия в <tt>.cpp</tt> необходимо наличие <tt>#include <KAction></tt><br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание объекта KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действий на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Комбинация клавиш=====<br />
<br />
Также, если ожидается что действие будет выполняться часто, с ним можно связать комбинацию клавиш. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение сигналов и слотов=====<br />
<br />
Теперь, когда параметры внешнего вида действия определены, можно связать его с методом tt>clear()</tt> объекта KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Интерфейс класса аналогичен {{qt|QAction}}, в KAction лишь добавлены специфические для KDE особенности.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit, save, и load, доступны готовые объекты KAction, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит пункт в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), следует использовать KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
<ActionList name="dynamicActionlist" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
Заметьте, что таким же способом можно динамически добавлять список действий, используя тэг <tt><ActionList></tt>. Для получения более подробной информации обратитесь к документации по методу <tt>plugActionList()</tt> класса {{class|KXMLGUIClient}}. <br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы проверить её (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=12773Development/Tutorials/Using KActions (ru)2007-08-04T20:17:19Z<p>Powerfox: /* Сборка, установка и запуск */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Использование действий является наиболее общим способом создания интерактивности программы.<br />
<br />
Например, требуется очищать текстовое поле нажатием кнопки на панели инструментов, клавиши быстрого выбора или при использовании какого-либо пункта меню File. Это можно обеспечить при помощи одного {{class|KAction}} (действия).<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Для создания действия в <tt>.cpp</tt> необходимо наличие <tt>#include <KAction></tt><br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание объекта KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действий на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Клавиша быстрого вызова=====<br />
<br />
Также с действием можно связать клавишу быстрого вызова. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение действий=====<br />
<br />
Теперь, когда действие полностью настроено, можно соединить его с действием <tt>clear()</tt>, принадлежащим KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Это абсолютно идентично использованию {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit', 'save', и 'load', существуют готовые KActions, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), следует использовать KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы проверить её (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=12772Development/Tutorials/Using KActions (ru)2007-08-04T20:13:14Z<p>Powerfox: /* Добавление действия в меню и на панель управления */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Использование действий является наиболее общим способом создания интерактивности программы.<br />
<br />
Например, требуется очищать текстовое поле нажатием кнопки на панели инструментов, клавиши быстрого выбора или при использовании какого-либо пункта меню File. Это можно обеспечить при помощи одного {{class|KAction}} (действия).<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Для создания действия в <tt>.cpp</tt> необходимо наличие <tt>#include <KAction></tt><br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание объекта KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действий на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Клавиша быстрого вызова=====<br />
<br />
Также с действием можно связать клавишу быстрого вызова. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение действий=====<br />
<br />
Теперь, когда действие полностью настроено, можно соединить его с действием <tt>clear()</tt>, принадлежащим KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Это абсолютно идентично использованию {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit', 'save', и 'load', существуют готовые KActions, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), следует использовать KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы его проверить (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=12771Development/Tutorials/Using KActions (ru)2007-08-04T20:09:09Z<p>Powerfox: /* Значок */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Использование действий является наиболее общим способом создания интерактивности программы.<br />
<br />
Например, требуется очищать текстовое поле нажатием кнопки на панели инструментов, клавиши быстрого выбора или при использовании какого-либо пункта меню File. Это можно обеспечить при помощи одного {{class|KAction}} (действия).<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Для создания действия в <tt>.cpp</tt> необходимо наличие <tt>#include <KAction></tt><br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание объекта KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действий на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Клавиша быстрого вызова=====<br />
<br />
Также с действием можно связать клавишу быстрого вызова. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение действий=====<br />
<br />
Теперь, когда действие полностью настроено, можно соединить его с действием <tt>clear()</tt>, принадлежащим KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Это абсолютно идентично использованию {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit', 'save', и 'load', существуют готовые KActions, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), мы использем KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы его проверить (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=12770Development/Tutorials/Using KActions (ru)2007-08-04T20:08:20Z<p>Powerfox: /* Создание объекта KAction */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Использование действий является наиболее общим способом создания интерактивности программы.<br />
<br />
Например, требуется очищать текстовое поле нажатием кнопки на панели инструментов, клавиши быстрого выбора или при использовании какого-либо пункта меню File. Это можно обеспечить при помощи одного {{class|KAction}} (действия).<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Для создания действия в <tt>.cpp</tt> необходимо наличие <tt>#include <KAction></tt><br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание объекта KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действия на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Клавиша быстрого вызова=====<br />
<br />
Также с действием можно связать клавишу быстрого вызова. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение действий=====<br />
<br />
Теперь, когда действие полностью настроено, можно соединить его с действием <tt>clear()</tt>, принадлежащим KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Это абсолютно идентично использованию {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit', 'save', и 'load', существуют готовые KActions, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), мы использем KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы его проверить (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=12769Development/Tutorials/Using KActions (ru)2007-08-04T20:07:44Z<p>Powerfox: /* Создание действий */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Использование действий является наиболее общим способом создания интерактивности программы.<br />
<br />
Например, требуется очищать текстовое поле нажатием кнопки на панели инструментов, клавиши быстрого выбора или при использовании какого-либо пункта меню File. Это можно обеспечить при помощи одного {{class|KAction}} (действия).<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Для создания действия в <tt>.cpp</tt> необходимо наличие <tt>#include <KAction></tt><br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действия на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Клавиша быстрого вызова=====<br />
<br />
Также с действием можно связать клавишу быстрого вызова. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение действий=====<br />
<br />
Теперь, когда действие полностью настроено, можно соединить его с действием <tt>clear()</tt>, принадлежащим KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Это абсолютно идентично использованию {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit', 'save', и 'load', существуют готовые KActions, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), мы использем KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы его проверить (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=12768Development/Tutorials/Using KActions (ru)2007-08-04T20:07:22Z<p>Powerfox: /* Создание действий */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Использование действий является наиболее общим способом создания интерактивности программы.<br />
<br />
Например, требуется очищать текстовое поле нажатием кнопки на панели инструментов, клавиши быстрого выбора или при использовании какого-либо пункта меню File. Это можно обеспечить при помощи одного {{class|KAction}} (действия).<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Для создания действия в <tt>.cpp</tt> <br />
необходимо наличие <tt>#include <KAction></tt><br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действия на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Клавиша быстрого вызова=====<br />
<br />
Также с действием можно связать клавишу быстрого вызова. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение действий=====<br />
<br />
Теперь, когда действие полностью настроено, можно соединить его с действием <tt>clear()</tt>, принадлежащим KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Это абсолютно идентично использованию {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit', 'save', и 'load', существуют готовые KActions, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), мы использем KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы его проверить (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=12767Development/Tutorials/Using KActions (ru)2007-08-04T20:05:33Z<p>Powerfox: /* Создание действий */</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Использование действий является наиболее общим способом создания интерактивности программы.<br />
<br />
Например, требуется очищать текстовое поле нажатием кнопки на панели инструментов, клавиши быстрого выбора или при использовании какого-либо пункта меню File. Это можно обеспечить при помощи одного {{class|KAction}} (действия).<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Чтобы создать действие необходимо включить в свой <tt>.cpp</tt> файл заголовочный файл <KAction></tt><br />
<br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действия на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Клавиша быстрого вызова=====<br />
<br />
Также с действием можно связать клавишу быстрого вызова. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение действий=====<br />
<br />
Теперь, когда действие полностью настроено, можно соединить его с действием <tt>clear()</tt>, принадлежащим KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Это абсолютно идентично использованию {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit', 'save', и 'load', существуют готовые KActions, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), мы использем KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы его проверить (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/First_program_(ru)&diff=12766Development/Tutorials/First program (ru)2007-08-04T20:03:40Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/First_program}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Hello World|<br />
<br />
pre=[http://mindview.net/Books/TICPP/ThinkingInCPP2e.html C++], [http://www.trolltech.com/products/qt/ Qt], [[Getting_Started/Build/KDE4_(ru)|Сборка и настройка KDE4]]|<br />
<br />
next=[[Development/Tutorials/Using_KXmlGuiWindow_%28ru%29|Урок 2 - KXmlGuiWindow]]| <br />
<br />
reading=[[Development/Tutorials/CMake|CMake]]<br />
}}<br />
<br />
==Введение==<br />
Первая программа приветствует мир дружелюбным "Hello World". Для этого будет использован {{class|KMessageBox}} с изменением одной из кнопок.<br />
[[image:introtokdetutorial1.png|frame|center]]<br />
<br />
{{tip|Для получения большей информации о каком-либо классе, с которым вы работаете, Konqueror предоставляет возможность быстрого вызова справки. Таким образом, чтобы посмотреть информацию о KMessageBox, просто введите "kde:kmessagebox" в Konqueror, и будет открыта документация.}}<br />
<br />
{{tip|<br />
Для работы с проектами можно использовать KDevelop, имеющий такие функции, как дополнение кода, лёгкий доступ к документации по API или поддержка отладки, удобство которых вы обязательно оцените после получения минимального опыта программирования.<br />
<br />
В [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|этом документе]] описывается настройка KDevelop для данной задачи. Проверить, работают ли настройки, можно попробовав открыть проект существующего приложения KDE4 с помощью KDevelop.<br />
<br />
Тем не менее, файлы CMake по-прежнему нужно редактировать вручную.<br />
}}<br />
<br />
==Код==<br />
Весь необходимый код находится в <tt>main.cpp</tt>. Создайте файл с кодом, приведённым ниже:<br />
<code cppqt><br />
#include <QString><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KMessageBox><br />
#include <KCmdLineArgs><br />
#include <KLocalizedString><br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData("tutorial1", // Имя программы используется для внутренних нужд.<br />
0, // Имя директории с сообщением (The message catalog name), используется имя программы, если 0.<br />
ki18n("Tutorial 1"), // Отображаемое имя программы.<br />
"1.0", // Строка с информацией о версии программы.<br />
ki18n("KMessageBox popup"), // Краткое описание того, что делает программа.<br />
KAboutData::License_GPL, // Тип лицензии.<br />
ki18n("(c) 2007"), // Заявление об авторском праве.<br />
ki18n("Some text..."), // Произвольный текст, содержащий информацию любого рода.<br />
"http://tutorial.com", // Адрес домашней страницы программы<br />
"submit@bugs.kde.org"); // Строка с адресом электронной почты для сообщений об ошибках.<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 />
<br />
Первый KDE код, который был встречен в программе - {{class|KAboutData}}. Это специальный класс для хранения такой информации о программе, как краткое описание, авторы, тип лицензии. Почти каждое (Pretty much) KDE-приложение должно использовать этот класс.<br />
<br />
Затем был использован {{class|KCmdLineArgs}}. Этот класс позволяет задать параметры командной строки, например, чтобы запускать программу с заданным файлом. Однако, в этом туториале мы просто инициализировали этот класс с помощью созданного объекта {{class|KAboutData}}. Так что можно использовать параметры командной строки <tt>--version</tt> or <tt>--author</tt>.<br />
<br />
В строке 13 был создан объект {{class|KApplication}}. Он нужен для таких вещей, как [[Development/Tutorials/Localization/i18n|поддержка перевода программ на другие языки]].<br />
<br />
Теперь, когда все требуемые начальные действия относящиеся к KDE выполнены, можно перейти к созданию интересных вещей для нашего приложения. Мы собираемся сделать всплывающее окно (popup box), кроме того, мы изменим одну из кнопок. Чтобы это сделать, нужен объект {{class|KGuiItem}}. Первый аргумент в конструкторе {{class|KGuiItem}} - текст, который отображается на элементе (в нашем случае - кнопке). Следующий параметр - значок для кнопки, но нам это не нужно, поэтому мы опускаем его, написав <tt>QString()</tt>. Наконец, мы задаём текст всплывающей подсказки (который появляется при наведении курсора на элемент) и текст для "What's This(Что это такое)?" (доступно через правый щелчок мышью или же Shift-F1)<br />
<br />
Теперь элемент настроен, и мы можем создать всплывающее окно (popup). Для этого вызывается функция <tt>KMessageBox::questionYesNo()</tt>, которая по умолчанию создаёт MessageBox с кнопками "Да", "Нет". Второй аргумент - текст, который будет выведен посередине диалогового окна.<br />
Третий - заголовок, который будет задан для окна и, наконец, мы используем KGuiItem (что будет нормально работать) для кнопки "Да" в <tt>KGuiItem guiItem</tt>, который нами создан.<br />
<br />
Теперь, когда мы закончили ознакомление с кодом, время собрать и запустить наше приложение.<br />
<br />
==Сборка==<br />
Если системное окружение было настроена так, как описано в [[Getting_Started/Build/KDE4|Getting_Started/Build/Unstable_Version]], то код можно скомпилировать так:<br />
<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 />
А затем запустить с помощью <br />
dbus-launch ./tutorial1<br />
<br />
===Использование CMake===<br />
Процесс сборки автоматизируется с помощью [[Development/Tutorials/CMake|CMake]]. Он самостоятельно определяет расположение библиотек и заголовочных файлов KDE, Qt и др. Использование CMake упрощает сборку приложения на другом компьютере.<br />
<br />
====CMakeLists.txt====<br />
Создайте файл с именем CMakeLists.txt со следующим содержанием в той же директории, что и main.cpp <br />
<code><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 />
<br />
Функция <tt>find_package()</tt> находит заданный пакет (в данном случае KDE4) и устанавливает определённые переменные, описывающие расположение заголовков и библиотек пакета. В данном примере использована переменная <tt>KDE4_INCLUDES</tt>, которая содержит путь к заголовочным файлам KDE4.<br />
<br />
Чтобы компилятор нашёл эти файлы, нужно передать эту переменную функции <tt>include_directories()</tt>, которая добавит директорию с заголовками KDE4 в поиск (search path).<br />
<br />
Далее была создана переменная <tt>tutorial1_SRCS</tt>, инициализированная с помощью функции <tt>set()</tt>. В данном случае, ей было просто задано имя исходного файла.<br />
<br />
Затем была использована функция <tt>kde4_add_executable()</tt>, чтобы создать исполняемый файл <tt>tutorial1</tt> из исходных файлов, перечисленных в переменной <tt>tutorial1_SRCS</tt>. Наконец, указывается библиотека KDE4 kdeui для линковки с файлом с помощью <tt>target_link_libraries()</tt> и переменной <tt>KDE4_KDEUI_LIBS</tt>, заданной с помощью функции <tt>find_package()</tt>.<br />
<br />
====Выполнение сборки и запуск (Make and Run)====<br />
Опять же, если системное окружение было установлено так, как описано в [[Getting_Started/Build/KDE4|Getting_Started/Build/Unstable_Version]], данный исходный код можно скомпилировать с помощью<br />
cmakekde<br />
<br />
И запустить<br />
./tutorial1.shell<br />
<br />
==Продолжим изучение==<br />
Теперь можно перейти к [[Development/Tutorials/Using_KXmlGuiWindow|статье о KXmlGuiWindow]].<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KXmlGuiWindow_(ru)&diff=12765Development/Tutorials/Using KXmlGuiWindow (ru)2007-08-04T20:02:28Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KXmlGuiWindow}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KXmlGuiWindow|<br />
<br />
pre=[[Development/Tutorials/First_program_(ru)|Урок 1 - Hello World]]|<br />
<br />
next=[[Development/Tutorials/Using_KActions_(ru)|Урок 3 - KActions and XmlGui]]| <br />
<br />
reading={{class|KXmlGuiWindow}}<br />
}}<br />
<br />
==Введение==<br />
Это продолжение [[Development/Tutorials/First_program|урока по созданию первой программы]], здесь представлена базовая информация по классу {{class|KXmlGuiWindow}}.<br />
<br />
В предыдущем уроке рассказывалось как создать всплывающее диалоговое окно, теперь мы сделаем первые шаги по созданию полноценного функционального приложения.<br />
<br />
[[image:introtokdetutorial2.png|frame|center]]<br />
<br />
==Использование KXmlGuiWindow==<br />
<br />
Чтобы получить пользу on KXmlGuiWindow, следует создать производный от него класс. Наш код находится в двух файлах: <tt>mainwindow.cpp</tt> и <tt>mainwindow.h</tt>. Класс KXmlGuiWindow выбран базовым, так как с помощью него можно использовать XML, например, чтобы определить структуру меню нашего приложения.<br />
<br />
===mainwindow.h===<br />
<code cppqt><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 />
Сначала в строке 7 мы объявляем производный от KXmlGuiWindow класс: <tt>class MainWindow : public KXmlGuiWindow</tt>, а затем - конструктор <tt>MainWindow(QWidget *parent=0);</tt>.<br />
<br />
И наконец, объявляем указатель на объект, который станет главной частью нашей программы. {{class|KTextEdit}} является базовым редактором текста в формате richtext, поддерживающем некоторые вкусности KDE, как, например, автоматическое скрытие курсора.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt><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 />
Сначала, конечно же, в строке 1 мы включаем заголовочный файл, содержащий объявление класса.<br />
<br />
В строке 5 создаётся объект нашего текстового редактора. Затем в строке 6 мы используем встроенную функцию setCentralWidget(), указывающую KXmlGuiWindow, что должно находиться в центральной секции нашего окна.<br />
<br />
Наконец, вызывается функция KXmlGuiWindow::setupGUI(), фоново выполняющая много различных действий по инициализации GUI и создающая панель меню по умолчанию (Settings, Help).<br />
<br />
<br />
==Создание main.cpp==<br />
Чтобы завершить создание приложение, нужно написать пару строк в main.cpp:<br />
===main.cpp===<br />
<code cppqt><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 />
Новыми (по сравнению с Уроком 1) являются только строки 18 и 19. В строке 18 мы создаём объект MainWindow и в строке 17 делаем его видимым. <br />
<br />
<br />
==CMake==<br />
Наилучший способ собрать наше приложение - использовать CMake. Все изменения по сравнению с уроком 1 заключаются в добавлении файла <tt>mainwindow.cpp</tt> в список исходников и смене названия <tt>tutorial1</tt> на <tt>tutorial2</tt>.<br />
<br />
===CMakeLists.txt===<br />
<code ini><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 />
===Компиляция===<br />
Чтобы скомпилировать, слинковать и запустить приложение, выполните:<br />
cmake . && make && ./tutorial2<br />
<br />
==Продолжим изучение==<br />
Теперь можно перейти к статье о [[Development/Tutorials/Using_KActions|KActions]].<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=12764Development/Tutorials/Using KActions (ru)2007-08-04T20:02:00Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_(ru)|Урок 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Использование действий является наиболее общим способом создания интерактивности программы.<br />
<br />
Например, требуется очищать текстовое поле нажатием кнопки на панели инструментов, клавиши быстрого выбора или при использовании какого-либо пункта меню File. Это можно обеспечить при помощи одного {{class|KAction}} (действия).<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Чтобы создать действие необходимо включить в свой <tt>.cpp</tt> файл заголовок <KAction></tt><br />
<br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действия на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Клавиша быстрого вызова=====<br />
<br />
Также с действием можно связать клавишу быстрого вызова. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение действий=====<br />
<br />
Теперь, когда действие полностью настроено, можно соединить его с действием <tt>clear()</tt>, принадлежащим KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Это абсолютно идентично использованию {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit', 'save', и 'load', существуют готовые KActions, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), мы использем KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы его проверить (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions_(ru)&diff=12763Development/Tutorials/Using KActions (ru)2007-08-04T19:54:51Z<p>Powerfox: Added russian translation</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KActions и XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow_%28ru%29<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Введение==<br />
В данном уроке представлена базовая информация по работе с элементами actions (действиями). Использование действий является наиболее общим способом создания интерактивности программы.<br />
<br />
Например, требуется очищать текстовое поле нажатием кнопки на панели инструментов, клавиши быстрого выбора или при использовании какого-либо пункта меню File. Это можно обеспечить при помощи одного {{class|KAction}} (действия).<br />
<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
Объект класса {{class|KAction}} хранит информацию о значке и клавише быстрого вызова, связанных с определённым действием. Действие может быть соединено со [http://doc.trolltech.com/latest/signalsandslots.html слотом], обрабатывающем его.<br />
<br />
<br />
===Создание действий===<br />
<br />
Чтобы создать действие необходимо включить в свой <tt>.cpp</tt> файл заголовок <KAction></tt><br />
<br />
=====Создание объекта KAction=====<br />
Мы создадим действие, очищающее текстовое поле (см. Урок 2). KAction создаётся в несколько шагов. Первый - создание KAction:<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
Этот код создаёт действие <tt>clearAction</tt>.<br />
<br />
<br />
=====Текст=====<br />
Теперь, когда объект KAction создан, можно приступить к его настройке. Сначала, мы задаём текст, отображаемый в меню и под значком на панели инструментов.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
Если планируется перевод интерфейса, то следует использовать функцию i18n для обработки текста.<br />
<br />
<br />
=====Значок=====<br />
<br />
При добавлении действия на панель инструментов можно задать значок, характеризующий выполняемое действие. Для этого следует просто вызвать функцию <tt>setIcon()</tt>, например: <br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
В данном примере с действием связывается стандартный значок KDE <tt>filenew</tt>.<br />
<br />
=====Клавиша быстрого вызова=====<br />
<br />
Также с действием можно связать клавишу быстрого вызова. Например, следующий фрагмент кода связывает с нашим действием комбинацию клавиш Ctrl+W:<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
<br />
<br />
=====Добавдение в набор (Collection)=====<br />
<br />
Чтобы сделать наше действие доступным системе XmlGui, следует добавить его в ''набор действий (action collection)'' приложения c помощью <tt>actionCollection()</tt> следующим образом:<br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
В данном примере мы добавляем <tt>clearAction</tt> в коллекцию, задав имя ''clear''. Это имя используется системой XmlGui.<br />
<br />
<br />
=====Соединение действий=====<br />
<br />
Теперь, когда действие полностью настроено, можно соединить его с действием <tt>clear()</tt>, принадлежащим KTextArea.<br />
<code cppqt><br />
connect( clearAction, SIGNAL( triggered(bool) ), <br />
textArea, SLOT( clear() ) );<br />
</code><br />
Это абсолютно идентично использованию {{qt|QAction}}.<br />
<br />
===KStandardAction===<br />
<br />
Для часто используемых в KDE приложениях действий, таких, как quit', 'save', и 'load', существуют готовые KActions, доступные через класс {{class|KStandardAction}}.<br />
<br />
Их очень легко использовать. После включения заголовочного файла <tt><KStandardAction></tt> в ваш код, следует просто соединить их с функциями-обработчиками и добавить в соответствующую коллекцию (KActionCollection). Например, следующий код<br />
<br />
<code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code><br />
создаст действие с соответствующим значком, текстом, клавишей быстрого вызова и даже добавит в меню File.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
<br />
==Добавление действия в меню и на панель управления==<br />
<br />
На данном этапе действие "Clear" только создано: оно не будет отображено в меню или на панели управления. Чтобы задать, куда следует добавить действия (и позволить пользователю программы перемещать их), мы использем KDE-технологию XmlGui. <br />
<br />
===XmlGui===<br />
<br />
{{note|В последующих версиях KDE4, XmlGui может быть заменена на систему liveui. Но сейчас XmlGui является единственным верным способом настройки UI.}}<br />
<br />
При вызове функции <tt>setupGUI()</tt> в нашем классе (производном) {{class|KXmlGuiWindow}}, осуществляется обращение к системе XmlGui, которая читатет XML файл с описанием интерфейса (мы рассмотрим его позже) и создаёт кнопки и меню.<br />
<br />
Очевидно, что XmlGui требуется знать, какой файл является файлом описания, т.е. его имя и расположение. По установленному правилу имя файла должно быть <tt>appnameui.rc</tt> (где <tt>appname</tt> является именем, заданным в {{class|KAboutData}}), таким образом, в нашем примере файл должен быть назван <tt>tutorial3ui.rc</tt>. Его расположение определяется CMake.<br />
<br />
===Создание файла ''appname''ui.rc ===<br />
<br />
В связи с тем, что UI описывается на языке XML, порядок описания должен придерживаться строгих правил. В данном уроке мы не станем подробно рассказывать обо всех правилах, но для получения большей информации рекомендуется посмотреть страницу _с_подробным_описанием_XML (когда у нас будет статья с полным описанием XmlGui (или, возможно, liveui, если эта система будет реализована :)) здесь будет соответсвующая ссылка).<br />
<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><br />
<Action name="clear" /><br />
</Menu><br />
</MenuBar><br />
</gui><br />
</code><br />
<br />
Тэг <tt><Toolbar></tt> служит для описания панели инструментов (toolbar). Панель инструментов - это панель со значками, находящаяся в верхней части окна. В данном примере она получила уникальное имя ''mainToolBar'' и с помощью <tt><text></tt> видимое пользователю имя ''Main Toolbar'', также мы добавляем на панель наше действие, используя тэг <tt><Action></tt>. Значение, заданное в параметре name, должно быть идентичным строке, переданной функции <tt>addAction()</tt> в нашем С++ коде.<br />
<br />
Теперь можно добавить действие в меню. Для этого мы используем тэг <tt><MenuBar></tt>, в остальном всё абсолютно идентично выше описаному.<br />
<br />
При изменении .rc файла следует изменять атрибут 'version', чтобы обновить кэш.<br />
<br />
==CMake==<br />
Из-за того, что был использован XmlGui, необходимо копировать <tt>tutorial3ui.rc</tt> туда, где KDE сможет его найти. '''Это означает, что необходимо куда-нибудь установить наш проект.'''<br />
<br />
===CMakeLists.txt===<br />
<code><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 />
Данный файл почти идентичен файлу со второго урока, но имеет две дополнительные строки. Они как раз и описывают, куда должны быть установлены файлы. Сначала в <tt>BIN_INSTALL_DIR</tt> будет установлен <tt>tutorial3</tt> (бинарный файл, target), затем в каталог приложения (data directory) - файл <tt>tutorial3ui.rc</tt>, описывающий пользовательский интерфейс.<br />
<br />
===Сборка, установка и запуск===<br />
Если у вас нет доступа к каталогу KDE4, то приложение можно установить в папку домашнего каталога. <br />
<br />
Чтобы указать CMake, куда следует установить программу, нужно использовать переменную <tt>DCMAKE_INSTALL_PREFIX</tt>. Таким образом, чтобы установить программу в каталог KDE, выполните:<br />
<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
<br />
Однако, если вы хотите установить программу куда-либо, чтобы его проверить (было бы глупо устанавливать приложения с этих уроков в каталог KDE), следует напечатать:<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
это создаст KDE-подобную структуру каталогов в ~/kdetmp и установит исполняемый файл в <br />
{{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
<br />
==Продолжим изучение==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions&diff=12762Development/Tutorials/Using KActions2007-08-04T19:51:05Z<p>Powerfox: Added Language Navigation Bar</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}<br />
<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=How To Use KActions and XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow|Tutorial 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Abstract==<br />
We're going to introduce the concept of actions. Actions are a unified way of supplying the user with ways to interact with your program.<br />
<br />
Say, for example, we want to let the user clear the text box by clicking a button in the toolbar, from an option in the File menu or through a keyboard shortcut; we can provide all of those through one {{class|KAction}}.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
A {{class|KAction}} is an object which contains all the information about the icon and shortcuts you want associated to a certain action. You then connect the action to a [http://doc.trolltech.com/latest/signalsandslots.html slot] which carries out the work of your action.<br />
<br />
===Creating Your Own===<br />
<br />
To create an action, you need to <tt>#include <KAction></tt> in your <tt>.cpp</tt> file. <br />
=====Creating the object=====<br />
We're going to create an action which will clear the text area (see Tutorial 2). The KAction is built up in a number of steps. The first is creating the KAction<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
This creates a KAction called <tt>clearAction</tt>.<br />
=====Text=====<br />
Now we have our KAction object, we can start setting its properties. First, we'll set the text that will be displayed in the menu and under its icon in the toolbar.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
As you can see, the text must be passed through the i18n() function if you want your UI to be translatable.<br />
<br />
=====Icon=====<br />
If you're going to display the action in a toolbar, you're going to want to have an icon depicting the action. To set an icon we simply use the <tt>setIcon()</tt> function thus:<br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
Here we're setting the icon to the standard KDE <tt>filenew</tt> icon.<br />
=====Shortcut=====<br />
We can also set a shortcut that will perform our action. It's as simple as a<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
to set Ctrl+W to be associated to this action.<br />
=====Adding to the Collection=====<br />
In order for our action to be accessable by the XmlGui framework it must be added to the application's ''action collection''. It is accessed via the <tt>actionCollection()</tt> function thus: <br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Here we add the <tt>clearAction</tt> KAction to the collection and give it a name of ''clear''. This name is used by the XmlGui framework.<br />
=====Connecting the action=====<br />
Now our action is fully set up, we need to connect it to something useful. We're going to connect our action to the <tt>clear()</tt> action belonging to a KTextArea.<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 {{class|KStandardAction}}.<br />
<br />
They are very simple to use. Once you've done <tt>#include <KStandardAction></tt>, you simply need to 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 />
Will Create a KAction with the correct icon, text and shortcut and will even add it to the File menu.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
==Putting the actions in the menus and toolbars==<br />
Now, at the moment, we've only created our new "Clear" action. It won't yet show up in the menus or in the toolbars. To tell the program where to put our actions (and to allow the end-user to move them around) we use a KDE technology called XmlGui.<br />
===XmlGui===<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 />
When you call <tt>setupGUI()</tt> in your {{class|KXmlGuiWindow}} class, it calls the XmlGui system which reads an XML file description of your interface (which we will create in a minute) and creates the buttons and menus appropriately.<br />
<br />
Now obviously XmlGui needs to know which file is your description file, i.e. it needs to know its name and location. The rule for the naming is the file should be called <tt>appnameui.rc</tt> (where <tt>appname</tt> is the name you set in {{class|KAboutData}}), so in our example, the file will be called <tt>tutorial3ui.rc</tt>. Where the file will be located is handled by CMake.<br />
<br />
===Writing your ''appname''ui.rc File===<br />
<br />
Since the description of our UI is being defined with XML, the layout of the description must follow strict rules. We won't go through all the rules in this tutorial but for more information, see the _detailed_XmlGui_page_ (once we have a full explanation of XmlGui (or possibly liveui if that's done soon :)) on the wiki, I'll link it up).<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><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. That is the bar across the top of the window with the icons. Here we give it a unique name ''mainToolBar'', set it's user visible name ''Main Toolbar'' using the <tt><text></tt> tag and finally add our clear action to the toolbar using the <tt><Action></tt> tag. The name parameter in this tag relates to the string that was passed to the <tt>addAction()</tt> function in the C++ code.<br />
<br />
As well as having our action in the toolbar, we can also add it to the menubar. Within the <tt><MenuBar></tt> tag, we say we want to add our action to the ''File'' menu and we add the action in the same way as for the toolbar.<br />
<br />
Change 'version' attribute of the gui tag if you changed .rc file since last install to force system cache update<br />
<br />
==CMake==<br />
Now that we're using XmlGui, we need to put the <tt>tutorial3ui.rc</tt> somewhere where KDE can find it. '''This means we need to install our project somewhere.'''<br />
===CMakeLists.txt===<br />
<code><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 it has two extra lines at the end. These 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. So to install the program to the KDE directory, do<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
Though, if you 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) you can do something like<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
which will create a KDE-like directory structure under ~/kdetmp and will install the executable to {{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KActions&diff=12761Development/Tutorials/Using KActions2007-08-04T18:50:29Z<p>Powerfox: /* CMakeLists.txt */</p>
<hr />
<div>{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=How To Use KActions and XmlGui|<br />
<br />
pre=[[Development/Tutorials/Using_KXmlGuiWindow|Tutorial 2 - KXmlGuiWindow]], Basic XML knowledge|<br />
<br />
next=TODO (milliams)| <br />
<br />
reading=None<br />
}}<br />
<br />
==Abstract==<br />
We're going to introduce the concept of actions. Actions are a unified way of supplying the user with ways to interact with your program.<br />
<br />
Say, for example, we want to let the user clear the text box by clicking a button in the toolbar, from an option in the File menu or through a keyboard shortcut; we can provide all of those through one {{class|KAction}}.<br />
<br />
[[image:introtokdetutorial3.png|frame|center]]<br />
<br />
==KAction==<br />
A {{class|KAction}} is an object which contains all the information about the icon and shortcuts you want associated to a certain action. You then connect the action to a [http://doc.trolltech.com/latest/signalsandslots.html slot] which carries out the work of your action.<br />
<br />
===Creating Your Own===<br />
<br />
To create an action, you need to <tt>#include <KAction></tt> in your <tt>.cpp</tt> file. <br />
=====Creating the object=====<br />
We're going to create an action which will clear the text area (see Tutorial 2). The KAction is built up in a number of steps. The first is creating the KAction<br />
<code cppqt>KAction* clearAction = new KAction(this);</code><br />
This creates a KAction called <tt>clearAction</tt>.<br />
=====Text=====<br />
Now we have our KAction object, we can start setting its properties. First, we'll set the text that will be displayed in the menu and under its icon in the toolbar.<br />
<code cppqt>clearAction->setText(i18n("Clear"));</code><br />
As you can see, the text must be passed through the i18n() function if you want your UI to be translatable.<br />
<br />
=====Icon=====<br />
If you're going to display the action in a toolbar, you're going to want to have an icon depicting the action. To set an icon we simply use the <tt>setIcon()</tt> function thus:<br />
<code cppqt>clearAction->setIcon(KIcon("filenew"));</code><br />
Here we're setting the icon to the standard KDE <tt>filenew</tt> icon.<br />
=====Shortcut=====<br />
We can also set a shortcut that will perform our action. It's as simple as a<br />
<code cppqt>clearAction->setShortcut(Qt::CTRL+Qt::Key_W);</code><br />
to set Ctrl+W to be associated to this action.<br />
=====Adding to the Collection=====<br />
In order for our action to be accessable by the XmlGui framework it must be added to the application's ''action collection''. It is accessed via the <tt>actionCollection()</tt> function thus: <br />
<code cppqt><br />
actionCollection()->addAction("clear", clearAction);<br />
</code><br />
Here we add the <tt>clearAction</tt> KAction to the collection and give it a name of ''clear''. This name is used by the XmlGui framework.<br />
=====Connecting the action=====<br />
Now our action is fully set up, we need to connect it to something useful. We're going to connect our action to the <tt>clear()</tt> action belonging to a KTextArea.<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 {{class|KStandardAction}}.<br />
<br />
They are very simple to use. Once you've done <tt>#include <KStandardAction></tt>, you simply need to 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 />
Will Create a KAction with the correct icon, text and shortcut and will even add it to the File menu.<br />
<br />
==The Code==<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 />
<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("filenew"));<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 />
===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 />
<br />
==Putting the actions in the menus and toolbars==<br />
Now, at the moment, we've only created our new "Clear" action. It won't yet show up in the menus or in the toolbars. To tell the program where to put our actions (and to allow the end-user to move them around) we use a KDE technology called XmlGui.<br />
===XmlGui===<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 />
When you call <tt>setupGUI()</tt> in your {{class|KXmlGuiWindow}} class, it calls the XmlGui system which reads an XML file description of your interface (which we will create in a minute) and creates the buttons and menus appropriately.<br />
<br />
Now obviously XmlGui needs to know which file is your description file, i.e. it needs to know its name and location. The rule for the naming is the file should be called <tt>appnameui.rc</tt> (where <tt>appname</tt> is the name you set in {{class|KAboutData}}), so in our example, the file will be called <tt>tutorial3ui.rc</tt>. Where the file will be located is handled by CMake.<br />
<br />
===Writing your ''appname''ui.rc File===<br />
<br />
Since the description of our UI is being defined with XML, the layout of the description must follow strict rules. We won't go through all the rules in this tutorial but for more information, see the _detailed_XmlGui_page_ (once we have a full explanation of XmlGui (or possibly liveui if that's done soon :)) on the wiki, I'll link it up).<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 />
<br />
<ToolBar name="mainToolBar" ><br />
<text>Main Toolbar</text><br />
<Action name="clear" /><br />
</ToolBar><br />
<MenuBar><br />
<Menu name="file" ><br />
<text>&amp;File</text><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. That is the bar across the top of the window with the icons. Here we give it a unique name ''mainToolBar'', set it's user visible name ''Main Toolbar'' using the <tt><text></tt> tag and finally add our clear action to the toolbar using the <tt><Action></tt> tag. The name parameter in this tag relates to the string that was passed to the <tt>addAction()</tt> function in the C++ code.<br />
<br />
As well as having our action in the toolbar, we can also add it to the menubar. Within the <tt><MenuBar></tt> tag, we say we want to add our action to the ''File'' menu and we add the action in the same way as for the toolbar.<br />
<br />
Change 'version' attribute of the gui tag if you changed .rc file since last install to force system cache update<br />
<br />
==CMake==<br />
Now that we're using XmlGui, we need to put the <tt>tutorial3ui.rc</tt> somewhere where KDE can find it. '''This means we need to install our project somewhere.'''<br />
===CMakeLists.txt===<br />
<code><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 it has two extra lines at the end. These 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. So to install the program to the KDE directory, do<br />
cmake . -DCMAKE_INSTALL_PREFIX=$KDEDIR<br />
make install<br />
tutorial3<br />
Though, if you 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) you can do something like<br />
cmake . -DCMAKE_INSTALL_PREFIX=/home/kde-devel/kdetmp<br />
which will create a KDE-like directory structure under ~/kdetmp and will install the executable to {{path|/home/kde-devel/kdetmp/bin/tutorial3}}.<br />
<br />
==Moving On==<br />
TODO<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=User_talk:Dhaumann&diff=12698User talk:Dhaumann2007-07-31T17:15:36Z<p>Powerfox: Thanks</p>
<hr />
<div>== Title Translation ==<br />
<br />
Hi guy !!!<br />
I would like to know if menu bar translation is possible... If true, how could I do this?<br />
Thank you...<br />
<br />
:You can use the template <nowiki>{{DISPLAYTITLE:foo}}</nowiki>, where 'foo' is the translation. However, the display title reflects the wiki link, that's why a text "link to this page as <nowiki>[[...]]</nowiki>" will appear then. --[[User:Dhaumann|Dhaumann]] 15:40, 18 June 2007 (CEST)<br />
<br />
::Actually not, I have hidden that text with display:none for on-screen printing. One bug though: When using DISPLAYTITLE, the <title> tag is not filled for some reason... --[[User:Danimo|Danimo]] 16:33, 18 June 2007 (CEST)<br />
<br />
:::Damn... If you need help with this, you can ask me as you want for help... ;) --[[User:Fatalerrors|Fatalerrors]] 10:52, 20 June 2007 (CEST)<br />
<br />
----<br />
<br />
Hi, Dhaumann, can you read and write Chinese? Cool! --[[User:Liangqi|Liangqi]] 23:00, 18 June 2007 (CEST)<br />
<br />
: Unfortunately no. I can't read nor write it. But I still try my best to fix links in a language where I mostly see squares :-) --[[User:Dhaumann|Dhaumann]] 23:22, 18 June 2007 (CEST)<br />
<br />
:: I see, I had found it in the diff. Thanks. I had mentioned this link problem in our mailing list. --[[User:Liangqi|Liangqi]] 11:36, 20 June 2007 (CEST)<br />
<br />
== Thanks ==<br />
<br />
Hi, Dhaumann, thanks for links fixes.<br />
I had fixed the link you were talking about.<br />
Thanks a lot.<br />
--[[User:Powerfox|Powerfox]] 19:15, 31 July 2007 (CEST)</div>Powerfoxhttps://techbase.kde.org/index.php?title=User:Powerfox&diff=12697User:Powerfox2007-07-31T17:10:34Z<p>Powerfox: </p>
<hr />
<div>Hello. My name is Evgeniy Ivanov. I study Computer Engineering. I'm still student and will study for a long time (about 4 years). I like programming, but at this time I may help KDE only as translator. Also I have a little module in fpc project (it's not written yet).<br />
--[[User:Powerfox|Powerfox]] 19:10, 31 July 2007 (CEST)</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/First_program_(ru)&diff=12676Development/Tutorials/First program (ru)2007-07-31T14:30:14Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/First_program}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Hello World|<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_%28ru%29|Урок 2 - KXmlGuiWindow]]| <br />
<br />
reading=[[Development/Tutorials/CMake|CMake]]<br />
}}<br />
<br />
==Введение==<br />
Первая программа приветствует мир дружелюбным "Hello World". Для этого будет использован {{class|KMessageBox}} с изменением одной из кнопок.<br />
[[image:introtokdetutorial1.png|frame|center]]<br />
<br />
{{tip|Для получения большей информации о каком-либо классе, с которым вы работаете, Konqueror предоставляет возможность быстрого вызова справки. Таким образом, чтобы посмотреть информацию о KMessageBox, просто введите "kde:kmessagebox" в Konqueror, и будет открыта документация.}}<br />
<br />
{{tip|<br />
Для работы с проектами можно использовать KDevelop, имеющий такие функции, как дополнение кода, лёгкий доступ к документации по API или поддержка отладки, удобство которых вы обязательно оцените после получения минимального опыта программирования.<br />
<br />
В [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|этом документе]] описывается настройка KDevelop для данной задачи. Проверить, работают ли настройки, можно попробовав открыть проект существующего приложения KDE4 с помощью KDevelop.<br />
<br />
Тем не менее, файлы CMake по-прежнему нужно редактировать вручную.<br />
}}<br />
<br />
==Код==<br />
Весь необходимый код находится в <tt>main.cpp</tt>. Создайте файл с кодом, приведённым ниже:<br />
<code cppqt><br />
#include <QString><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KMessageBox><br />
#include <KCmdLineArgs><br />
#include <KLocalizedString><br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData("tutorial1", // Имя программы используется для внутренних нужд.<br />
0, // Имя директории с сообщением (The message catalog name), используется имя программы, если 0.<br />
ki18n("Tutorial 1"), // Отображаемое имя программы.<br />
"1.0", // Строка с информацией о версии программы.<br />
ki18n("KMessageBox popup"), // Краткое описание того, что делает программа.<br />
KAboutData::License_GPL, // Тип лицензии.<br />
ki18n("(c) 2007"), // Заявление об авторском праве.<br />
ki18n("Some text..."), // Произвольный текст, содержащий информацию любого рода.<br />
<br />
"http://tutorial.com", // Адрес домашней страницы программы<br />
"submit@bugs.kde.org"); // Строка с адресом электронной почты для сообщений об ошибках.<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 />
<br />
Первый KDE код, который был встречен в программе - {{class|KAboutData}}. Это специальный класс для хранения такой информации о программе, как краткое описание, авторы, тип лицензии. Почти каждое (Pretty much) KDE-приложение должно использовать этот класс.<br />
<br />
Затем был использован {{class|KCmdLineArgs}}. Этот класс позволяет задать параметры командной строки, например, чтобы запускать программу с заданным файлом. Однако, в этом туториале мы просто инициализировали этот класс с помощью созданного объекта {{class|KAboutData}}. Так что можно использовать параметры командной строки <tt>--version</tt> or <tt>--author</tt>.<br />
<br />
В строке 13 был создан объект {{class|KApplication}}. Он нужен для таких вещей, как [[Development/Tutorials/Localization/i18n|поддержка перевода программ на другие языки]].<br />
<br />
Теперь, когда все требуемые начальные действия относящиеся к KDE выполнены, можно перейти к созданию интересных вещей для нашего приложения. Мы собираемся сделать всплывающее окно (popup box), кроме того, мы изменим одну из кнопок. Чтобы это сделать, нужен объект {{class|KGuiItem}}. Первый аргумент в конструкторе {{class|KGuiItem}} - текст, который отображается на элементе (в нашем случае - кнопке). Следующий параметр - значок для кнопки, но нам это не нужно, поэтому мы опускаем его, написав <tt>QString()</tt>. Наконец, мы задаём текст всплывающей подсказки (который появляется при наведении курсора на элемент) и текст для "What's This(Что это такое)?" (доступно через правый щелчок мышью или же Shift-F1)<br />
<br />
Теперь элемент настроен, и мы можем создать всплывающее окно (popup). Для этого вызывается функция <tt>KMessageBox::questionYesNo()</tt>, которая по умолчанию создаёт MessageBox с кнопками "Да", "Нет". Второй аргумент - текст, который будет выведен посередине диалогового окна.<br />
Третий - заголовок, который будет задан для окна и, наконец, мы используем KGuiItem (что будет нормально работать) для кнопки "Да" в <tt>KGuiItem guiItem</tt>, который нами создан.<br />
<br />
Теперь, когда мы закончили ознакомление с кодом, время собрать и запустить наше приложение.<br />
<br />
==Сборка==<br />
Если системное окружение было настроена так, как описано в [[Getting_Started/Build/KDE4|Getting_Started/Build/Unstable_Version]], то код можно скомпилировать так:<br />
<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 />
А затем запустить с помощью <br />
dbus-launch ./tutorial1<br />
<br />
===Использование CMake===<br />
Процесс сборки автоматизируется с помощью [[Development/Tutorials/CMake|CMake]]. Он самостоятельно определяет расположение библиотек и заголовочных файлов KDE, Qt и др. Использование CMake упрощает сборку приложения на другом компьютере.<br />
<br />
====CMakeLists.txt====<br />
Создайте файл с именем CMakeLists.txt со следующим содержанием в той же директории, что и main.cpp <br />
<code><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 />
<br />
Функция <tt>find_package()</tt> находит заданный пакет (в данном случае KDE4) и устанавливает определённые переменные, описывающие расположение заголовков и библиотек пакета. В данном примере использована переменная <tt>KDE4_INCLUDES</tt>, которая содержит путь к заголовочным файлам KDE4.<br />
<br />
Чтобы компилятор нашёл эти файлы, нужно передать эту переменную функции <tt>include_directories()</tt>, которая добавит директорию с заголовками KDE4 в поиск (search path).<br />
<br />
Далее была создана переменная <tt>tutorial1_SRCS</tt>, инициализированная с помощью функции <tt>set()</tt>. В данном случае, ей было просто задано имя исходного файла.<br />
<br />
Затем была использована функция <tt>kde4_add_executable()</tt>, чтобы создать исполняемый файл <tt>tutorial1</tt> из исходных файлов, перечисленных в переменной <tt>tutorial1_SRCS</tt>. Наконец, указывается библиотека KDE4 kdeui для линковки с файлом с помощью <tt>target_link_libraries()</tt> и переменной <tt>KDE4_KDEUI_LIBS</tt>, заданной с помощью функции <tt>find_package()</tt>.<br />
<br />
====Выполнение сборки и запуск (Make and Run)====<br />
Опять же, если системное окружение было установлено так, как описано в [[Getting_Started/Build/KDE4|Getting_Started/Build/Unstable_Version]], данный исходный код можно скомпилировать с помощью<br />
cmakekde<br />
<br />
И запустить<br />
./tutorial1.shell<br />
<br />
==Продолжим изучение==<br />
Теперь можно перейти к [[Development/Tutorials/Using_KXmlGuiWindow|статье о KXmlGuiWindow]].<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KXmlGuiWindow_(ru)&diff=12675Development/Tutorials/Using KXmlGuiWindow (ru)2007-07-31T14:26:49Z<p>Powerfox: Added russian translation</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KXmlGuiWindow}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Использование KMainWindow|<br />
<br />
pre=[[Development/Tutorials/First_program|Урок 1 - Hello World]]|<br />
<br />
next=[[Development/Tutorials/Using_KActions|Урок 3 - KActions and XmlGui]]| <br />
<br />
reading={{class|KMainWindow}}<br />
}}<br />
<br />
==Введение==<br />
Этот продолжение [[Development/Tutorials/Programming_Tutorial_KDE_4/First_program|урока по созданию первой программы]], здесь представлена базовая информация об использовании класса {{class|KXmlGuiWindow}}.<br />
<br />
В предыдущем уроке рассказывалось, как создать всплывающее диалоговое окно, теперь мы сделаем несколько шагов вперёд к созданию полноценного функционального приложения.<br />
<br />
[[image:introtokdetutorial2.png|frame|center]]<br />
<br />
==Использование KXmlGuiWindow==<br />
<br />
Чтобы получить пользу on KXmlGuiWindow, следует создать производный от него класс. Наш код находится в двух файлах: <tt>mainwindow.cpp</tt> и <tt>mainwindow.h</tt>. Класс KXmlGuiWindow выбран базовым, так как с помощью него можно использовать XML, например, чтобы определить структуру меню нашего приложения.<br />
<br />
===mainwindow.h===<br />
<code cppqt><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 />
Сначала в строке 7 мы объявляем производный от KXmlGuiWindow класс: <tt>class MainWindow : public KXmlGuiWindow</tt>, а затем - конструктор <tt>MainWindow(QWidget *parent=0);</tt>.<br />
<br />
И наконец, объявляем указатель на объект, который станет главной частью нашей программы. {{class|KTextEdit}} является базовым редактором текста в формате richtext, поддерживающем некоторые вкусности KDE, как, например, автоматическое скрытие курсора.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt><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 />
Сначала, конечно же, в строке 1 мы включаем заголовочный файл, содержащий объявление класса.<br />
<br />
В строке 5 создаётся объект нашего текстового редактора. Затем в строке 6 мы используем встроенную функцию setCentralWidget(), указывающую KXmlGuiWindow, что должно находиться в центральной секции нашего окна.<br />
<br />
Наконец, вызывается функция KXmlGuiWindow::setupGUI(), фоново выполняющая много различных действий по инициализации GUI и создающая панель меню по умолчанию (Settings, Help).<br />
<br />
<br />
==Создание main.cpp==<br />
Чтобы завершить создание приложение, нужно написать пару строк в main.cpp:<br />
===main.cpp===<br />
<code cppqt><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 />
Новыми (по сравнению с Уроком 1) являются только строки 18 и 19. В строке 18 мы создаём объект MainWindow и в строке 17 делаем его видимым. <br />
<br />
<br />
==CMake==<br />
Наилучший способ собрать наше приложение - использовать CMake. Все изменения по сравнению с уроком 1 заключаются в добавлении файла <tt>mainwindow.cpp</tt> в список исходников и смене названия <tt>tutorial1</tt> на <tt>tutorial2</tt>.<br />
<br />
===CMakeLists.txt===<br />
<code ini><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 />
===Компиляция===<br />
Чтобы скомпилировать, слинковать и запустить приложение, выполните:<br />
cmake . && make && ./tutorial2<br />
<br />
==Продолжим изучение==<br />
Теперь можно перейти к статье о [[Development/Tutorials/Using_KActions|KActions]].<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KXmlGuiWindow&diff=12674Development/Tutorials/Using KXmlGuiWindow2007-07-31T14:25:22Z<p>Powerfox: Added Language Navigation Bar</p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KXmlGuiWindow}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=How To Use KMainWindow|<br />
<br />
pre=[[Development/Tutorials/First_program|Tutorial 1 - Hello World]]|<br />
<br />
next=[[Development/Tutorials/Using_KActions|Tutorial 3 - KActions and XmlGui]]| <br />
<br />
reading={{class|KMainWindow}}<br />
}}<br />
<br />
==Abstract==<br />
This tutorial carries on from [[Development/Tutorials/Programming_Tutorial_KDE_4/First_program|First Program Tutorial]] and will introduce the {{class|KXmlGuiWindow}} class.<br />
<br />
In the previous tutorial, the program caused a dialog box to pop up but we're going to take steps towards a functioning application.<br />
<br />
[[image:introtokdetutorial2.png|frame|center]]<br />
<br />
==Using KXmlGuiWindow==<br />
<br />
In order to have a useful KXmlGuiWindow, we must subclass it. So we create two files, a <tt>mainwindow.cpp</tt> and a <tt>mainwindow.h</tt> which will contain our code. Our class inherits from KXmlGuiWindow because it uses XML e.g. to define the application's menu structure.<br />
<br />
===mainwindow.h===<br />
<code cppqt><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 />
First we Subclass KXmlGuiWindow on line 7 with with <tt>class MainWindow : public KXmlGuiWindow</tt>.<br />
<br />
Then we declare the constructor with <tt>MainWindow(QWidget *parent=0);</tt>.<br />
<br />
And finally we declare a pointer to the object that will make up the bulk of our program. {{class|KTextEdit}} is a generic richtext editor with some KDE niceties like cursor auto-hiding.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt><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 />
First, of course, on line 1 we have to include the header file containing the class declaration.<br />
<br />
On line 5, we initialise our text editor with an object. Then on line 6 we use the built-in setCentralWidget() function which tells the KXmlGuiWindow what should appear in the central section of the window.<br />
<br />
Finally, KXmlGuiWindow::setupGUI() is called which does a lot of behind-the-scenes stuff and creates the default menu bars (Settings, Help).<br />
<br />
==Back to main.cpp==<br />
In order to actually run this window, we need to add a few lines in main.cpp:<br />
===main.cpp===<br />
<code cppqt><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 />
The only new lines here (compared to Tutorial 1) are 18 and 19. On line 18, we create our MainWindow object and then on line 19, we display it.<br />
<br />
==CMake==<br />
The best way to build the program is to use CMake. All that's changed since tutorial 1 is that <tt>mainwindow.cpp</tt> has been added to the sources list and any <tt>tutorial1</tt> has become <tt>tutorial2</tt>.<br />
===CMakeLists.txt===<br />
<code ini><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 />
===Compile it===<br />
To compile, link and run it, use:<br />
cmake . && make && ./tutorial2<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Using_KActions|using KActions]].<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/First_program_(ru)&diff=12670Development/Tutorials/First program (ru)2007-07-31T13:28:20Z<p>Powerfox: </p>
<hr />
<div>{{Template:I18n/Language Navigation Bar|Development/Tutorials/First_program}}<br />
{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=Hello World|<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|Урок 2 - KXmlGuiWindow]]| <br />
<br />
reading=[[Development/Tutorials/CMake|CMake]]<br />
}}<br />
<br />
==Введение==<br />
Первая программа приветствует мир дружелюбным "Hello World". Для этого будет использован {{class|KMessageBox}} с изменением одной из кнопок.<br />
[[image:introtokdetutorial1.png|frame|center]]<br />
<br />
{{tip|Для получения большей информации о каком-либо классе, с которым вы работаете, Konqueror предоставляет возможность быстрого вызова справки. Таким образом, чтобы посмотреть информацию о KMessageBox, просто введите "kde:kmessagebox" в Konqueror, и будет открыта документация.}}<br />
<br />
{{tip|<br />
Для работы с проектами можно использовать KDevelop, имеющий такие функции, как дополнение кода, лёгкий доступ к документации по API или поддержка отладки, удобство которых вы обязательно оцените после получения минимального опыта программирования.<br />
<br />
В [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|этом документе]] описывается настройка KDevelop для данной задачи. Проверить, работают ли настройки, можно попробовав открыть проект существующего приложения KDE4 с помощью KDevelop.<br />
<br />
Тем не менее, файлы CMake по-прежнему нужно редактировать вручную.<br />
}}<br />
<br />
==Код==<br />
Весь необходимый код находится в <tt>main.cpp</tt>. Создайте файл с кодом, приведённым ниже:<br />
<code cppqt><br />
#include <QString><br />
#include <KApplication><br />
#include <KAboutData><br />
#include <KMessageBox><br />
#include <KCmdLineArgs><br />
#include <KLocalizedString><br />
<br />
int main (int argc, char *argv[])<br />
{<br />
KAboutData aboutData("tutorial1", // Имя программы используется для внутренних нужд.<br />
0, // Имя директории с сообщением (The message catalog name), используется имя программы, если 0.<br />
ki18n("Tutorial 1"), // Отображаемое имя программы.<br />
"1.0", // Строка с информацией о версии программы.<br />
ki18n("KMessageBox popup"), // Краткое описание того, что делает программа.<br />
KAboutData::License_GPL, // Тип лицензии.<br />
ki18n("(c) 2007"), // Заявление об авторском праве.<br />
ki18n("Some text..."), // Произвольный текст, содержащий информацию любого рода.<br />
<br />
"http://tutorial.com", // Адрес домашней страницы программы<br />
"submit@bugs.kde.org"); // Строка с адресом электронной почты для сообщений об ошибках.<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 />
<br />
Первый KDE код, который был встречен в программе - {{class|KAboutData}}. Это специальный класс для хранения такой информации о программе, как краткое описание, авторы, тип лицензии. Почти каждое (Pretty much) KDE-приложение должно использовать этот класс.<br />
<br />
Затем был использован {{class|KCmdLineArgs}}. Этот класс позволяет задать параметры командной строки, например, чтобы запускать программу с заданным файлом. Однако, в этом туториале мы просто инициализировали этот класс с помощью созданного объекта {{class|KAboutData}}. Так что можно использовать параметры командной строки <tt>--version</tt> or <tt>--author</tt>.<br />
<br />
В строке 13 был создан объект {{class|KApplication}}. Он нужен для таких вещей, как [[Development/Tutorials/Localization/i18n|поддержка перевода программ на другие языки]].<br />
<br />
Теперь, когда все требуемые начальные действия относящиеся к KDE выполнены, можно перейти к созданию интересных вещей для нашего приложения. Мы собираемся сделать всплывающее окно (popup box), кроме того, мы изменим одну из кнопок. Чтобы это сделать, нужен объект {{class|KGuiItem}}. Первый аргумент в конструкторе {{class|KGuiItem}} - текст, который отображается на элементе (в нашем случае - кнопке). Следующий параметр - значок для кнопки, но нам это не нужно, поэтому мы опускаем его, написав <tt>QString()</tt>. Наконец, мы задаём текст всплывающей подсказки (который появляется при наведении курсора на элемент) и текст для "What's This(Что это такое)?" (доступно через правый щелчок мышью или же Shift-F1)<br />
<br />
Теперь элемент настроен, и мы можем создать всплывающее окно (popup). Для этого вызывается функция <tt>KMessageBox::questionYesNo()</tt>, которая по умолчанию создаёт MessageBox с кнопками "Да", "Нет". Второй аргумент - текст, который будет выведен посередине диалогового окна.<br />
Третий - заголовок, который будет задан для окна и, наконец, мы используем KGuiItem (что будет нормально работать) для кнопки "Да" в <tt>KGuiItem guiItem</tt>, который нами создан.<br />
<br />
Теперь, когда мы закончили ознакомление с кодом, время собрать и запустить наше приложение.<br />
<br />
==Сборка==<br />
Если системное окружение было настроена так, как описано в [[Getting_Started/Build/KDE4|Getting_Started/Build/Unstable_Version]], то код можно скомпилировать так:<br />
<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 />
А затем запустить с помощью <br />
dbus-launch ./tutorial1<br />
<br />
===Использование CMake===<br />
Процесс сборки автоматизируется с помощью [[Development/Tutorials/CMake|CMake]]. Он самостоятельно определяет расположение библиотек и заголовочных файлов KDE, Qt и др. Использование CMake упрощает сборку приложения на другом компьютере.<br />
<br />
====CMakeLists.txt====<br />
Создайте файл с именем CMakeLists.txt со следующим содержанием в той же директории, что и main.cpp <br />
<code><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 />
<br />
Функция <tt>find_package()</tt> находит заданный пакет (в данном случае KDE4) и устанавливает определённые переменные, описывающие расположение заголовков и библиотек пакета. В данном примере использована переменная <tt>KDE4_INCLUDES</tt>, которая содержит путь к заголовочным файлам KDE4.<br />
<br />
Чтобы компилятор нашёл эти файлы, нужно передать эту переменную функции <tt>include_directories()</tt>, которая добавит директорию с заголовками KDE4 в поиск (search path).<br />
<br />
Далее была создана переменная <tt>tutorial1_SRCS</tt>, инициализированная с помощью функции <tt>set()</tt>. В данном случае, ей было просто задано имя исходного файла.<br />
<br />
Затем была использована функция <tt>kde4_add_executable()</tt>, чтобы создать исполняемый файл <tt>tutorial1</tt> из исходных файлов, перечисленных в переменной <tt>tutorial1_SRCS</tt>. Наконец, указывается библиотека KDE4 kdeui для линковки с файлом с помощью <tt>target_link_libraries()</tt> и переменной <tt>KDE4_KDEUI_LIBS</tt>, заданной с помощью функции <tt>find_package()</tt>.<br />
<br />
====Выполнение сборки и запуск (Make and Run)====<br />
Опять же, если системное окружение было установлено так, как описано в [[Getting_Started/Build/KDE4|Getting_Started/Build/Unstable_Version]], данный исходный код можно скомпилировать с помощью<br />
cmakekde<br />
<br />
И запустить<br />
./tutorial1.shell<br />
<br />
==Продолжим изучение==<br />
Теперь можно перейти к [[Development/Tutorials/Using_KXmlGuiWindow|статье о KXmlGuiWindow]].<br />
<br />
[[Category:C++]]</div>Powerfoxhttps://techbase.kde.org/index.php?title=Development/Tutorials/Using_KXmlGuiWindow&diff=12669Development/Tutorials/Using KXmlGuiWindow2007-07-31T13:20:46Z<p>Powerfox: /* main.cpp */ Line numbers correction</p>
<hr />
<div>{{TutorialBrowser|<br />
<br />
series=Beginner Tutorial|<br />
<br />
name=How To Use KMainWindow|<br />
<br />
pre=[[Development/Tutorials/First_program|Tutorial 1 - Hello World]]|<br />
<br />
next=[[Development/Tutorials/Using_KActions|Tutorial 3 - KActions and XmlGui]]| <br />
<br />
reading={{class|KMainWindow}}<br />
}}<br />
<br />
==Abstract==<br />
This tutorial carries on from [[Development/Tutorials/Programming_Tutorial_KDE_4/First_program|First Program Tutorial]] and will introduce the {{class|KXmlGuiWindow}} class.<br />
<br />
In the previous tutorial, the program caused a dialog box to pop up but we're going to take steps towards a functioning application.<br />
<br />
[[image:introtokdetutorial2.png|frame|center]]<br />
<br />
==Using KXmlGuiWindow==<br />
<br />
In order to have a useful KXmlGuiWindow, we must subclass it. So we create two files, a <tt>mainwindow.cpp</tt> and a <tt>mainwindow.h</tt> which will contain our code. Our class inherits from KXmlGuiWindow because it uses XML e.g. to define the application's menu structure.<br />
<br />
===mainwindow.h===<br />
<code cppqt><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 />
First we Subclass KXmlGuiWindow on line 7 with with <tt>class MainWindow : public KXmlGuiWindow</tt>.<br />
<br />
Then we declare the constructor with <tt>MainWindow(QWidget *parent=0);</tt>.<br />
<br />
And finally we declare a pointer to the object that will make up the bulk of our program. {{class|KTextEdit}} is a generic richtext editor with some KDE niceties like cursor auto-hiding.<br />
<br />
===mainwindow.cpp===<br />
<code cppqt><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 />
First, of course, on line 1 we have to include the header file containing the class declaration.<br />
<br />
On line 5, we initialise our text editor with an object. Then on line 6 we use the built-in setCentralWidget() function which tells the KXmlGuiWindow what should appear in the central section of the window.<br />
<br />
Finally, KXmlGuiWindow::setupGUI() is called which does a lot of behind-the-scenes stuff and creates the default menu bars (Settings, Help).<br />
<br />
==Back to main.cpp==<br />
In order to actually run this window, we need to add a few lines in main.cpp:<br />
===main.cpp===<br />
<code cppqt><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 />
The only new lines here (compared to Tutorial 1) are 18 and 19. On line 18, we create our MainWindow object and then on line 19, we display it.<br />
<br />
==CMake==<br />
The best way to build the program is to use CMake. All that's changed since tutorial 1 is that <tt>mainwindow.cpp</tt> has been added to the sources list and any <tt>tutorial1</tt> has become <tt>tutorial2</tt>.<br />
===CMakeLists.txt===<br />
<code ini><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 />
===Compile it===<br />
To compile, link and run it, use:<br />
cmake . && make && ./tutorial2<br />
<br />
==Moving On==<br />
Now you can move on to [[Development/Tutorials/Using_KActions|using KActions]].<br />
<br />
[[Category:C++]]</div>Powerfox