Development/Tutorials/Using KActions (es): Difference between revisions

    From KDE TechBase
    No edit summary
    No edit summary
     
    (11 intermediate revisions by 3 users not shown)
    Line 1: Line 1:
    {{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KActions}}
     


    {{TutorialBrowser_(es)|
    {{TutorialBrowser_(es)|
    Line 9: Line 9:
    pre=[[Development/Tutorials/Using_KXmlGuiWindow_(es)|Tutorial 2 - KXmlGuiWindow]], Conocimiento básico de XML|
    pre=[[Development/Tutorials/Using_KXmlGuiWindow_(es)|Tutorial 2 - KXmlGuiWindow]], Conocimiento básico de XML|


    next=[[Development/Tutorials/Saving_and_loading|Tutorial 4 - Saving and loading]]|  
    next=[[Development/Tutorials/Saving_and_loading_(es)|Tutorial 4 - Guardar y Abrir]]|  


    reading=Nada
    reading=Nada
    Line 15: Line 15:


    ==Resumen==
    ==Resumen==
    This tutorial introduces the concept of actions. Actions are a unified way of supplying the user with ways to interact with your program.
    Este tutorial introduce el concepto de las acciones. Las acciones son una forma unificada de proporcionar al usuario la forma de interactuar con tu programa.


    For example, if we wanted to let the user of [[Development/Tutorials/Using_KXmlGuiWindow|Tutorial 2 ]] clear the text box by clicking a button in the toolbar, from an option in the File menu or through a keyboard shortcut, it could all be done with one {{class|KAction}}.
    Por ejemplo, si queremos permitir que el usuario del [[Development/Tutorials/Using_KXmlGuiWindow_(es)|Tutorial 2]] pueda borrar la caja de texto pulsando un botón de la barra de herramientas, desde una entrada del menú File o a través de un atajo de teclado, podremos realizarlo mediante un {{class|KAction}}.


    [[image:introtokdetutorial3.png|frame|center]]
    [[image:introtokdetutorial3_(es).png|frame|center]]


    ==KAction==
    ==KAction==
    A {{class|KAction}} is an object which contains all the information about the icon and shortcuts that is associated with a certain action. The action is then connected to a [http://doc.trolltech.com/latest/signalsandslots.html slot] which carries out the work of your action.
    Un {{class|KAction}} es un objeto que contiene toda la información sobre el icono y el atajo de teclado asociado a una determinada acción. La acción se conecta a un [http://doc.trolltech.com/latest/signalsandslots.html slot], que lleva a cabo el trabajo de la acción.


    == El código ==
    == El código ==


    ===main.cpp===
    ===main.cpp===
    <code cppqt n>
    <syntaxhighlight lang="cpp-qt" line>
    #include <KApplication>
    #include <KApplication>
    #include <KAboutData>
    #include <KAboutData>
    #include <KCmdLineArgs>
    #include <KCmdLineArgs>
     
    #include "mainwindow.h"
    #include "mainwindow.h"
     
    int main (int argc, char *argv[])
    int main (int argc, char *argv[])
    {
    {
       KAboutData aboutData( "tutorial3", "tutorial3",
       KAboutData aboutData( "tutorial3", "tutorial3",
           ki18n("Tutorial 3"), "1.0",
           ki18n("Tutorial 3"), "1.0",
           ki18n("A simple text area using KAction etc."),
           ki18n("Area de texto usando KAction."),
           KAboutData::License_GPL,
           KAboutData::License_GPL,
           ki18n("Copyright (c) 2007 Developer") );
           ki18n("Copyright (c) 2008 Developer") );
       KCmdLineArgs::init( argc, argv, &aboutData );
       KCmdLineArgs::init( argc, argv, &aboutData );
       KApplication app;
       KApplication app;
    Line 48: Line 48:
       return app.exec();
       return app.exec();
    }
    }
    </code>
    </syntaxhighlight>
    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.
    Pocas cosas han cambiado en <tt>main.cpp</tt>, solo se ha actualizado la declaración de KAboutData para indicar que ahora estamos en el tutorial 3.


    ===mainwindow.h===
    ===mainwindow.h===
    <code cppqt n>
    <syntaxhighlight lang="cpp-qt" line>
    #ifndef MAINWINDOW_H
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    #define MAINWINDOW_H
    Line 70: Line 70:


    #endif
    #endif
    </code>
    </syntaxhighlight>
    Only a function <tt>void setupActions()</tt> has been added which will do all the work setting up the KActions.
    Sólo se ha añadido la función <tt>void setupActions()</tt>, que realizará el trabajo de configurar los KActions.


    ===mainwindow.cpp===
    ===mainwindow.cpp===
    <code cppqt n>
    <syntaxhighlight lang="cpp-qt" line>
    #include "mainwindow.h"
    #include "mainwindow.h"
     
    #include <KApplication>
    #include <KApplication>
    #include <KAction>
    #include <KAction>
    Line 82: Line 82:
    #include <KActionCollection>
    #include <KActionCollection>
    #include <KStandardAction>
    #include <KStandardAction>
     
    MainWindow::MainWindow(QWidget *parent)
    MainWindow::MainWindow(QWidget *parent)
         : KXmlGuiWindow(parent)
         : KXmlGuiWindow(parent)
    Line 88: Line 88:
       textArea = new KTextEdit;
       textArea = new KTextEdit;
       setCentralWidget(textArea);
       setCentralWidget(textArea);
     
       setupActions();
       setupActions();
    }
    }
     
    void MainWindow::setupActions()
    void MainWindow::setupActions()
    {
    {
       KAction* clearAction = new KAction(this);
       KAction* clearAction = new KAction(this);
       clearAction->setText(i18n("Clear"));
       clearAction->setText(i18n("Limpiar"));
       clearAction->setIcon(KIcon("document-new"));
       clearAction->setIcon(KIcon("document-new"));
       clearAction->setShortcut(Qt::CTRL + Qt::Key_W);
       clearAction->setShortcut(Qt::CTRL + Qt::Key_W);
       actionCollection()->addAction("clear", clearAction);
       actionCollection()->addAction("limpiar", clearAction);
       connect(clearAction, SIGNAL(triggered(bool)),
       connect(clearAction, SIGNAL(triggered(bool)),
               textArea, SLOT(clear()));
               textArea, SLOT(clear()));
     
       KStandardAction::quit(kapp, SLOT(quit()),
       KStandardAction::quit(kapp, SLOT(quit()),
                             actionCollection());
                             actionCollection());
     
       setupGUI();
       setupGUI();
    }
    }
    </code>
     
    </syntaxhighlight>


    ==Explicación==
    ==Explicación==
    This builds upon the KXmlGuiWindow code from [[Development/Tutorials/Using_KXmlGuiWindow|Tutorial 2]]. Most of the changes are to <tt>mainwindow.cpp</tt>, an important structural change being that the constructor for MainWindow now calls <tt>setupActions()</tt> instead of <tt>setupGUI()</tt>. <tt>setupActions()</tt> is where the new KAction code goes before finally calling <tt>setupGUI()</tt> itself.
    El archivo está basado en el código de KXmlGuiWindow del [[Development/Tutorials/Using_KXmlGuiWindow_(es)|Tutorial 2]]. La mayoría de los cambios están en <tt>mainwindow.cpp</tt>, un cambio estructural importante es que el constructor de MainWindow ahora llama a <tt>setupActions()</tt> en vez de a <tt>setupGUI()</tt>. En <tt>setupActions()</tt> va el nuevo código de KAction antes de llamar a <tt>setupGUI()</tt>.


    ===Creando el objeto KAction===
    ===Creando el objeto KAction===
    The KAction is built up in a number of steps. The first is including the <tt>KAction</tt> library and then creating the KAction:
    KAction se construye en varios pasos. El primero es incluir la biblioteca <tt>KAction</tt> y crear el KAction:
    <code cppqt>
    <syntaxhighlight lang="cpp-qt">
    #include <KAction>
    #include <KAction>
    ...
    ...
    KAction* clearAction = new KAction(this);
    KAction* clearAction = new KAction(this);
    </code>
    </syntaxhighlight>
    This creates a new KAction called <tt>clearAction</tt>.
    Crear un KAction nuevo llamado <tt>clearAction</tt>.


    ===Estableciendo las propiedades de KAction===
    ===Estableciendo las propiedades de KAction===
    ====Texto====
    ====Texto====
    Now we have our KAction object, we can start setting its properties. The following code sets the text that will be displayed in the menu and under the <tt>KAction</tt>'s icon in the toolbar.
    Ahora que tenemos nuestro objeto KAction, podemos empezar a establecer sus propiedades. El siguiente código establece el texto que se mostrará en el menú y el de debajo del icono del <tt>KAction</tt> en la barra de herramientas:
    <code cppqt>clearAction->setText(i18n("Clear"));</code>
    <syntaxhighlight lang="cpp-qt">clearAction->setText(i18n("Limpiar"));</syntaxhighlight>
    Note that the text is passed through the i18n() function; this is necessary for the UI to be translatable (more information on this can be found in the [[Development/Tutorials/Localization/i18n|i18n tutorial]]).
    Ten en cuenta que el texto se pasa a través de la función i18n(), esto es necesario para para que la UI pueda ser traducida (puedes encontrar mas información en el [[Development/Tutorials/Localization/i18n|tutorial de i18n]]).


    ====Icono====
    ====Icono====
    If the action is going to be displayed in a toolbar, it's nice to have an icon depicting the action. The following code sets the icon to the standard KDE <tt>document-new</tt> icon through the use of the <tt>setIcon()</tt> function:
    Si la acción va a mostrarse en el la barra de herramientas, estaría bien que tuviera un icono que la representara. El siguiente código establece como icono el icono estándar de KDE <tt>document-new</tt> mediante el uso de la función <tt>setIcon()</tt>:
    <code cppqt>clearAction->setIcon(KIcon("document-new"));</code>
    <syntaxhighlight lang="cpp-qt">clearAction->setIcon(KIcon("document-new"));</syntaxhighlight>


    ====Atajo de teclado====
    ====Atajo de teclado====
    Setting a keyboard shortcut to perform our action is equally simple:
    Establecer un atajo de teclado para lanzar nuestra acción es igual de simple:
    <code cppqt>clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</code>
    <syntaxhighlight lang="cpp-qt">clearAction->setShortcut(Qt::CTRL + Qt::Key_W);</syntaxhighlight>
    This associates Ctrl+W with the KAction.
    Asocia Ctrl+W a la acción.


    ===Añadir a la colección===
    ===Añadir a la colección===
    In order for the action to be accessed by the XMLGUI framework (explained in depth later) it must be added to the application's ''action collection''. The action collection is accessed via the <tt>actionCollection()</tt> function like this:  
    Para que la acción sea accesible por el framework XMLGUI (explicado en profundidad mas adelante) debe añadirse a la ''colección de acciones'' de la aplicación. La colección de acciones es accesible mediante la función <tt>actionCollection()</tt>:  
    <code cppqt>
    <syntaxhighlight lang="cpp-qt">
    actionCollection()->addAction("clear", clearAction);
    actionCollection()->addAction("limpiar", clearAction);
    </code>
    </syntaxhighlight>
    Here, the <tt>clearAction</tt> KAction is added to the collection and given a name of ''clear''. This name (''clear'') is used by the XMLGUI framework to refer to the action.
    Con esta llamada, la KAction <tt>clearAction</tt> se añade a la colección y toma el nombre de ''limpiar''. Este nombre (''limpiar'') lo usa el framework XMLGUI para referirse a la acción.


    ====Conectando la acción====
    ====Conectando la acción====
    Now that the action is fully set up, it needs to be connected to something useful. In this case (because we want to clear the text area), we connect our action to the <tt>clear()</tt> action belonging to a KTextEdit (which, unsurprisingly, clears the KTextEdit)
    Ahora que hemos establecido la acción, es necesario conectarla a algo útil. En este caso (porque queremos limpiar el área de texto), conectamos nuestra acción con la acción <tt>clear()</tt> perteneciente a KTextEdit (que como era de esperar, limpia KTextEdit):
    <code cppqt>
    <syntaxhighlight lang="cpp-qt">
    connect( clearAction, SIGNAL( triggered(bool) ),  
    connect( clearAction, SIGNAL( triggered(bool) ),  
             textArea, SLOT( clear() ) );
             textArea, SLOT( clear() ) );
    </code>
    </syntaxhighlight>
    This is the same as it would be done in Qt with a {{qt|QAction}}.
    Es lo mismo que se llevaría a cabo en Qt con una {{qt|QAction}}.


    ===KStandardAction===
    ===KStandardAction===
    Para las acciones que normalmente aparecen en casi todas las aplicaciones KDE, como 'quit', 'save', y 'load', existen unas acciones ya creadas, accesibles a través de [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction].


    For actions which would likely appear in almost every KDE application such as 'quit', 'save', and 'load' there are pre-created convenience KActions, accessed through [http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/namespaceKStandardAction.html KStandardAction].
    Son muy sencillas de usar. Una vez que has incluido las bibliotecas (<tt>#include <KStandardAction></tt>), simplemente añadelas con la función que quieras que realicen. Por ejemplo:
     
    <syntaxhighlight lang="cpp-qt">KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</syntaxhighlight>
    They are very simple to use. Once the library has been included (<tt>#include <KStandardAction></tt>), simply supply it with what you want the function to do and which KActionCollection to add it to. For example:
    Crea una KAction con el icono correcto, el texto y el atajo de teclado, e incluso la añade al menú File.
    <code cppqt>KStandardAction::quit(kapp, SLOT(quit()), actionCollection());</code>
    This creates a KAction with the correct icon, text and shortcut and even adds it to the File menu.


    ==Añadir la acción a los menús y a las barras de herramientas==
    ==Añadir la acción a los menús y a las barras de herramientas==
    At the moment, the new "Clear" action has been created but it hasn't been associated with any menus or toolbars. This is done with a KDE technology called XMLGUI, which does nice things like movable toolbars for you.
    Por el momento, hemos creado la nueva acción "Limpiar" pero no se ha asociado a ningún menú o barra de herramientas. Esto lo podemos hacer con una tecnología de KDE llamada XMLGUI, que hace cosas majas como barras de herramientas móviles.


    {{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.}}
    {{note|En una versión posterior de KDE4, XMLGUI puede ser reemplazada por un nuevo framework llamado liveui. Por ahora, XMLGUI es la única manera correcta de configurar la UI.}}


    ==XMLGUI==
    ==XMLGUI==
    La función <tt>setupGUI()</tt> de la clase {{class|KXmlGuiWindow}} depende del sistema XMLGUI para construir la GUI, el cual la realiza analizando el archivo de descripción XML de la interfaz.


    The <tt>setupGUI()</tt> function in {{class|KXmlGuiWindow}} depends on the XMLGUI system to construct the GUI, which XMLGUI does by parsing an XML file description of the interface.
    La regla para establecer el nombre del archivo XML es <tt>appnameui.rc</tt>, donde <tt>appname</tt> es el nombre que estableces en {{class|KAboutData}} (en este caso, ''tutorial 3''). Por lo que en nuestro ejemplo, llamamos al archivo <tt>tutorial3ui.rc</tt>, y está localizado en el directorio del código. Cmake maneja donde será puesto el archivo en última instancia.  
     
    The rule for naming this XML file is <tt>appnameui.rc</tt>, where <tt>appname</tt> is the name you set in {{class|KAboutData}} (in this case, ''tutorial3''). So in our example, the file is called <tt>tutorial3ui.rc</tt>, and is located in the build directory. Where the file will ultimately be placed is handled by CMake.


    ==Archivo ''appname''ui.rc==
    ==Archivo ''appname''ui.rc==
     
    Como la descripción de la UI está definida en el archivo XML, el layout debe seguir unas reglas estrictas. Este tutorial no profundizará en exceso en este aspecto, pero para mas información puedes echar un vistazo a la [[Development/Architecture/KDE4/XMLGUI_Technology|página de XMLGUI]] (aquí tienes un tutorial antiguo: [http://developer.kde.org/documentation/tutorials/xmlui/preface.html])
    Since the description of the UI is defined with XML, the layout must follow strict rules. This tutorial will not go into great depth on this topic, but for more information, see the [[Development/Architecture/KDE4/XMLGUI_Technology|detailed XMLGUI page]] (here is an older tutorial: [http://developer.kde.org/documentation/tutorials/xmlui/preface.html]).


    ===tutorial3ui.rc===
    ===tutorial3ui.rc===
    <code xml n>
    <syntaxhighlight lang="xml" line>
    <?xml version="1.0" encoding="UTF-8"?>
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
    <gui name="tutorial3"
    <gui name="tutorial3" version="1">
        version="1"
      <ToolBar name="mainToolBar" >
        xmlns="http://www.kde.org/standards/kxmlgui/1.0"
        <text>Main Toolbar</text>
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        <Action name="clear" />
        xsi:schemaLocation="http://www.kde.org/standards/kxmlgui/1.0
      </ToolBar>
                            http://www.kde.org/standards/kxmlgui/1.0/kxmlgui.xsd" >
     
       <MenuBar>
       <MenuBar>
         <Menu name="file" >
         <Menu name="file" >
           <Action name="clear" />
           <Action name="limpiar" />
         </Menu>
         </Menu>
       </MenuBar>
       </MenuBar>
      <ToolBar name="mainToolBar" >
        <text>Main Toolbar</text>
        <Action name="limpiar" />
      </ToolBar>
    </gui>
    </gui>
    </code>
    </syntaxhighlight>
     
    La etiqueta <tt><Toolbar></tt> permite describir la barra de herramientas, que normalmente es la barra con los iconos de la parte superior de la ventana. Se le da el nombre único de ''mainToolBar'', y usando la etiqueta <tt><text></tt>, es visible a los usuarios con el nombre ''Main Toolbar''. La acción limpiae se añade a la barra de herramientas usando la etiqueta <tt><Action></tt>,  el nombre del parámetro en esta etiqueta es la cadena que pasamos a KActionCollection con <tt>addAction()</tt> en <tt>mainwindow.cpp</tt>.


    The <tt><Toolbar></tt> tag allows you to describe the toolbar, which is the bar across the top of the window normally with icons. Here it is given the unique name ''mainToolBar'' and its user visible name set to ''Main Toolbar'' using the <tt><text></tt> tag. The clear action is added to the toolbar using the <tt><Action></tt> tag, the name parameter in this tag being the string that was passed to the KActionCollection with <tt>addAction()</tt> in <tt>mainwindow.cpp</tt>.
    Además de tener la acción en la barra de herramientas, también se puede añadir a la barra de menú. Aquí la acción se ha añadido al menú ''File'' de <tt>MenuBar</tt> de la misma manera que la añadimos a la barra de herramientas.


    Besides having the action in the toolbar, it can also be added to the menubar. Here the action is being added to the ''File'' menu of the <tt>MenuBar</tt> the same way it was added to the toolbar.
    Cambia el atributo 'version' de la etiqueta <tt><nowiki><gui></nowiki></tt> si cambiaste el archivo .rc desde la última instalación, para forzar una actualización de la cache del sistema. Asegurate de que sea un entero, si usas un valor decimal no funcionará, pero no notificará que no lo hizo.


    Change the 'version' attribute of the <tt><nowiki><gui></nowiki></tt> tag if you changed .rc file since the last install to force a system cache update.
    Algunas notas sobre la interacción entre el código y el archivo .rc: Los menús aparecen automáticamente y deberían tener una etiqueta hija <tt><nowiki><text/></nowiki></tt> a menos que se refieran a los menús estándar. Las acciones deberán crearse manualmente y se insertarán mediante actionCollection() usando el nombre del archivo .rc. Las acciones pueden ocultarse o desactivarse, mientras que los menús no.


    Some notes on the interaction between code and the .rc file: Menus appear automatically and should have a <tt><nowiki><text/></nowiki></tt> child tag unless they refer to standard menus. Actions need to be created manually and inserted into the actionCollection() using the name in the .rc file. Actions can be hidden or disabled, whereas menus can't.


    ==CMake==
    ==CMake==
    Finally, the <tt>tutorial3ui.rc</tt> needs to go somewhere where KDE can find it (can't just leave it in the source directory!). '''This means the project needs to be installed somewhere.'''
    Por último, el <tt>tutorial3ui.rc</tt> hay que ubicarlo en algún lugar donde KDE pueda encontrarlo (no lo puedes dejar en el directorio de las fuentes!). '''Esto significa que el proyecto tiene que ser instalado en algún sitio'''.
    ===CMakeLists.txt===
    ===CMakeLists.txt===
    <code ini n>
    <syntaxhighlight lang="ini" line>
    project(tutorial3)
    project(tutorial3)


    Line 220: Line 226:
    install(FILES tutorial3ui.rc  
    install(FILES tutorial3ui.rc  
             DESTINATION  ${DATA_INSTALL_DIR}/tutorial3)
             DESTINATION  ${DATA_INSTALL_DIR}/tutorial3)
    </code>
    </syntaxhighlight>


    This file is almost identical to the one for tutorial2, but with two extra lines at the end that describe where the files are to be installed. Firstly, the <tt>tutorial3</tt> target is installed to the <tt>BIN_INSTALL_DIR</tt> then the <tt>tutorial3ui.rc</tt> file that describes the layout of the user interface is installed to the application's data directory.
    Este archivo es casi idéntico al del tutorial2, peor con dos lineas extra al final que describen donde se instalará los archivos. En primer lugar, el objetivo <tt>tutorial3</tt> se instala en <tt>BIN_INSTALL_DIR</tt>, entonces el archivo <tt>tutorial3ui.rc</tt> que describe el layout de la interfaz de usuario se instala en el directorio de datos de las aplicaciones.


    ===Make, instalar y ejecutar===
    ===Make, instalar y ejecutar===
    If you don't have write access to where your KDE4 installation directory, you can install it to a folder in your home directory.
    Si no tienes acceso de escritura a tu directorio de instalación de KDE4, puedes instalarlo en una carpeta de tu directorio personal.


    To tell CMake where to install the program, set the <tt>DCMAKE_INSTALL_PREFIX</tt> switch. You probably just want to install it somewhere local for testing (it's probably a bit silly to go to the effort of installing these tutorials to your KDE directory), so the following might be appropriate:
    Para decirle a CMake donde instalar el programa, establece la variable <tt>DCMAKE_INSTALL_PREFIX</tt>. Probablemente quieras instalarlo en algún sitio local para testearlo (probablemente sea un poco tonto hacer el esfuerzo de instalar estos tutoriales en el directorio de KDE), por lo que podría ser el siguiente caso:
      mkdir build && cd build
      mkdir build && cd build
      cmake .. -DCMAKE_INSTALL_PREFIX=$HOME
      cmake .. -DCMAKE_INSTALL_PREFIX=$HOME
      make install
      make install
      $HOME/bin/tutorial3
      $HOME/bin/tutorial3
    which will create a KDE-like directory structure in your user's home directory directory and will install the executable to {{path|$HOME/bin/tutorial3}}.
    Creará una estructura de directorios como la de KDE en tu directorio de usuario e instalara el ejecutable en {{path|$HOME/bin/tutorial3}}.


    ==Avanzando==
    ==Avanzando==
    Now you can move on to [[Development/Tutorials/Saving_and_loading|saving and loading]].
    Ahora puedes continuar con el [[Development/Tutorials/Saving_and_loading_(es)|Tutorial 4 - Guardar y Abrir]].


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

    Latest revision as of 16:25, 15 July 2012


    Como usar KActions y XMLGUI
    Serie   Tutorial para principiantes
    Requisitos previos   Tutorial 2 - KXmlGuiWindow, Conocimiento básico de XML
    Siguiente   Tutorial 4 - Guardar y Abrir
    Lectura avanzada   Nada

    Resumen

    Este tutorial introduce el concepto de las acciones. Las acciones son una forma unificada de proporcionar al usuario la forma de interactuar con tu programa.

    Por ejemplo, si queremos permitir que el usuario del Tutorial 2 pueda borrar la caja de texto pulsando un botón de la barra de herramientas, desde una entrada del menú File o a través de un atajo de teclado, podremos realizarlo mediante un KAction.

    KAction

    Un KAction es un objeto que contiene toda la información sobre el icono y el atajo de teclado asociado a una determinada acción. La acción se conecta a un slot, que lleva a cabo el trabajo de la acción.

    El código

    main.cpp

    #include <KApplication>
    #include <KAboutData>
    #include <KCmdLineArgs>
     
    #include "mainwindow.h"
     
    int main (int argc, char *argv[])
    {
      KAboutData aboutData( "tutorial3", "tutorial3",
          ki18n("Tutorial 3"), "1.0",
          ki18n("Area de texto usando KAction."),
          KAboutData::License_GPL,
          ki18n("Copyright (c) 2008 Developer") );
      KCmdLineArgs::init( argc, argv, &aboutData );
      KApplication app;
     
      MainWindow* window = new MainWindow();
      window->show();
      return app.exec();
    }
    

    Pocas cosas han cambiado en main.cpp, solo se ha actualizado la declaración de KAboutData para indicar que ahora estamos en el tutorial 3.

    mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <KXmlGuiWindow>
    #include <KTextEdit>
    
    class MainWindow : public KXmlGuiWindow
    {
      public:
        MainWindow(QWidget *parent=0);
    	
      private:
        KTextEdit* textArea;
        void setupActions();
    };
    
    #endif
    

    Sólo se ha añadido la función void setupActions(), que realizará el trabajo de configurar los KActions.

    mainwindow.cpp

    #include "mainwindow.h"
     
    #include <KApplication>
    #include <KAction>
    #include <KLocale>
    #include <KActionCollection>
    #include <KStandardAction>
     
    MainWindow::MainWindow(QWidget *parent)
        : KXmlGuiWindow(parent)
    {
      textArea = new KTextEdit;
      setCentralWidget(textArea);
     
      setupActions();
    }
     
    void MainWindow::setupActions()
    {
      KAction* clearAction = new KAction(this);
      clearAction->setText(i18n("Limpiar"));
      clearAction->setIcon(KIcon("document-new"));
      clearAction->setShortcut(Qt::CTRL + Qt::Key_W);
      actionCollection()->addAction("limpiar", clearAction);
      connect(clearAction, SIGNAL(triggered(bool)),
              textArea, SLOT(clear()));
     
      KStandardAction::quit(kapp, SLOT(quit()),
                            actionCollection());
     
      setupGUI();
    }
    

    Explicación

    El archivo está basado en el código de KXmlGuiWindow del Tutorial 2. La mayoría de los cambios están en mainwindow.cpp, un cambio estructural importante es que el constructor de MainWindow ahora llama a setupActions() en vez de a setupGUI(). En setupActions() va el nuevo código de KAction antes de llamar a setupGUI().

    Creando el objeto KAction

    KAction se construye en varios pasos. El primero es incluir la biblioteca KAction y crear el KAction:

    #include <KAction>
    ...
    KAction* clearAction = new KAction(this);
    

    Crear un KAction nuevo llamado clearAction.

    Estableciendo las propiedades de KAction

    Texto

    Ahora que tenemos nuestro objeto KAction, podemos empezar a establecer sus propiedades. El siguiente código establece el texto que se mostrará en el menú y el de debajo del icono del KAction en la barra de herramientas:

    clearAction->setText(i18n("Limpiar"));
    

    Ten en cuenta que el texto se pasa a través de la función i18n(), esto es necesario para para que la UI pueda ser traducida (puedes encontrar mas información en el tutorial de i18n).

    Icono

    Si la acción va a mostrarse en el la barra de herramientas, estaría bien que tuviera un icono que la representara. El siguiente código establece como icono el icono estándar de KDE document-new mediante el uso de la función setIcon():

    clearAction->setIcon(KIcon("document-new"));
    

    Atajo de teclado

    Establecer un atajo de teclado para lanzar nuestra acción es igual de simple:

    clearAction->setShortcut(Qt::CTRL + Qt::Key_W);
    

    Asocia Ctrl+W a la acción.

    Añadir a la colección

    Para que la acción sea accesible por el framework XMLGUI (explicado en profundidad mas adelante) debe añadirse a la colección de acciones de la aplicación. La colección de acciones es accesible mediante la función actionCollection():

    actionCollection()->addAction("limpiar", clearAction);
    

    Con esta llamada, la KAction clearAction se añade a la colección y toma el nombre de limpiar. Este nombre (limpiar) lo usa el framework XMLGUI para referirse a la acción.

    Conectando la acción

    Ahora que hemos establecido la acción, es necesario conectarla a algo útil. En este caso (porque queremos limpiar el área de texto), conectamos nuestra acción con la acción clear() perteneciente a KTextEdit (que como era de esperar, limpia KTextEdit):

    connect( clearAction, SIGNAL( triggered(bool) ), 
             textArea, SLOT( clear() ) );
    

    Es lo mismo que se llevaría a cabo en Qt con una QAction.

    KStandardAction

    Para las acciones que normalmente aparecen en casi todas las aplicaciones KDE, como 'quit', 'save', y 'load', existen unas acciones ya creadas, accesibles a través de KStandardAction.

    Son muy sencillas de usar. Una vez que has incluido las bibliotecas (#include <KStandardAction>), simplemente añadelas con la función que quieras que realicen. Por ejemplo:

    KStandardAction::quit(kapp, SLOT(quit()), actionCollection());
    

    Crea una KAction con el icono correcto, el texto y el atajo de teclado, e incluso la añade al menú File.

    Añadir la acción a los menús y a las barras de herramientas

    Por el momento, hemos creado la nueva acción "Limpiar" pero no se ha asociado a ningún menú o barra de herramientas. Esto lo podemos hacer con una tecnología de KDE llamada XMLGUI, que hace cosas majas como barras de herramientas móviles.

    Note
    En una versión posterior de KDE4, XMLGUI puede ser reemplazada por un nuevo framework llamado liveui. Por ahora, XMLGUI es la única manera correcta de configurar la UI.


    XMLGUI

    La función setupGUI() de la clase KXmlGuiWindow depende del sistema XMLGUI para construir la GUI, el cual la realiza analizando el archivo de descripción XML de la interfaz.

    La regla para establecer el nombre del archivo XML es appnameui.rc, donde appname es el nombre que estableces en KAboutData (en este caso, tutorial 3). Por lo que en nuestro ejemplo, llamamos al archivo tutorial3ui.rc, y está localizado en el directorio del código. Cmake maneja donde será puesto el archivo en última instancia.

    Archivo appnameui.rc

    Como la descripción de la UI está definida en el archivo XML, el layout debe seguir unas reglas estrictas. Este tutorial no profundizará en exceso en este aspecto, pero para mas información puedes echar un vistazo a la página de XMLGUI (aquí tienes un tutorial antiguo: [1])

    tutorial3ui.rc

    <?xml version="1.0" encoding="UTF-8"?>
    <gui name="tutorial3"
         version="1"
         xmlns="http://www.kde.org/standards/kxmlgui/1.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.kde.org/standards/kxmlgui/1.0
                             http://www.kde.org/standards/kxmlgui/1.0/kxmlgui.xsd" >
    
      <MenuBar>
        <Menu name="file" >
          <Action name="limpiar" />
        </Menu>
      </MenuBar>
    
      <ToolBar name="mainToolBar" >
        <text>Main Toolbar</text>
        <Action name="limpiar" />
      </ToolBar>
    
    </gui>
    

    La etiqueta <Toolbar> permite describir la barra de herramientas, que normalmente es la barra con los iconos de la parte superior de la ventana. Se le da el nombre único de mainToolBar, y usando la etiqueta <text>, es visible a los usuarios con el nombre Main Toolbar. La acción limpiae se añade a la barra de herramientas usando la etiqueta <Action>, el nombre del parámetro en esta etiqueta es la cadena que pasamos a KActionCollection con addAction() en mainwindow.cpp.

    Además de tener la acción en la barra de herramientas, también se puede añadir a la barra de menú. Aquí la acción se ha añadido al menú File de MenuBar de la misma manera que la añadimos a la barra de herramientas.

    Cambia el atributo 'version' de la etiqueta <gui> si cambiaste el archivo .rc desde la última instalación, para forzar una actualización de la cache del sistema. Asegurate de que sea un entero, si usas un valor decimal no funcionará, pero no notificará que no lo hizo.

    Algunas notas sobre la interacción entre el código y el archivo .rc: Los menús aparecen automáticamente y deberían tener una etiqueta hija <text/> a menos que se refieran a los menús estándar. Las acciones deberán crearse manualmente y se insertarán mediante actionCollection() usando el nombre del archivo .rc. Las acciones pueden ocultarse o desactivarse, mientras que los menús no.


    CMake

    Por último, el tutorial3ui.rc hay que ubicarlo en algún lugar donde KDE pueda encontrarlo (no lo puedes dejar en el directorio de las fuentes!). Esto significa que el proyecto tiene que ser instalado en algún sitio.

    CMakeLists.txt

    project(tutorial3)
    
    find_package(KDE4 REQUIRED)
    include_directories(${KDE4_INCLUDES})
    
    set(tutorial3_SRCS 
      main.cpp
      mainwindow.cpp
    )
    
    kde4_add_executable(tutorial3 ${tutorial3_SRCS})
    
    target_link_libraries(tutorial3 ${KDE4_KDEUI_LIBS})
    
    install(TARGETS tutorial3 DESTINATION ${BIN_INSTALL_DIR})
    install(FILES tutorial3ui.rc 
            DESTINATION  ${DATA_INSTALL_DIR}/tutorial3)
    

    Este archivo es casi idéntico al del tutorial2, peor con dos lineas extra al final que describen donde se instalará los archivos. En primer lugar, el objetivo tutorial3 se instala en BIN_INSTALL_DIR, entonces el archivo tutorial3ui.rc que describe el layout de la interfaz de usuario se instala en el directorio de datos de las aplicaciones.

    Make, instalar y ejecutar

    Si no tienes acceso de escritura a tu directorio de instalación de KDE4, puedes instalarlo en una carpeta de tu directorio personal.

    Para decirle a CMake donde instalar el programa, establece la variable DCMAKE_INSTALL_PREFIX. Probablemente quieras instalarlo en algún sitio local para testearlo (probablemente sea un poco tonto hacer el esfuerzo de instalar estos tutoriales en el directorio de KDE), por lo que podría ser el siguiente caso:

    mkdir build && cd build
    cmake .. -DCMAKE_INSTALL_PREFIX=$HOME
    make install
    $HOME/bin/tutorial3
    

    Creará una estructura de directorios como la de KDE en tu directorio de usuario e instalara el ejecutable en $HOME/bin/tutorial3.

    Avanzando

    Ahora puedes continuar con el Tutorial 4 - Guardar y Abrir.