KDE TechBase
  • Page
  • Discussion
  • Edit
  • History
KDE TechBase is a Wiki - You can help! Please contribute! Questions?
Please ask development related questions in the KDE Community Forum.

Development/Tutorials/KCmdLineArgs (es)

< Development | Tutorials

Languages: عربي | Asturianu | Català | Česky | Kaszëbsczi | Dansk | Deutsch | English | Esperanto | Español | فارسی | Suomi | Français | Galego | Italiano | 日本語 | 한국어 | Norwegian | Polski | Português Brasileiro | Română | Русский | Svenska | Slovenščina | српски | Українська | 简体中文 | 繁體中文

Argumentos para la linea de ordenes
Serie   Tutorial para principiantes
Requisitos previos   Tutorial 4 - Cargar y Guardar
Siguiente   Tutorial 6 - ### (TODO User:milliams)
Lectura avanzada   KCmdLineArgs KCmdLineOptions

Contents

  • 1 Resumen
  • 2 El código
    • 2.1 main.cpp
    • 2.2 mainwindow.h
    • 2.3 mainwindow.cpp
    • 2.4 tutorial5ui.rc
  • 3 Explicación
    • 3.1 mainwindow.h
    • 3.2 mainwindow.cpp
    • 3.3 main.cpp
  • 4 Make, Instalar y Ejecutar
    • 4.1 CMakeLists.txt

[edit] Resumen

Ahora que tenemos el editor de texto con el cual podemos cargar y guardar archivos, vamos a hacer que actúe mas como una aplicación de escritorio, permitiendo cargar archivos desde la linea de ordenes e incluso usar Abrir con en Dolphin.

[edit] El código

[edit] main.cpp

  1. #include <KApplication>
  2. #include <KAboutData>
  3. #include <KCmdLineArgs>
  4. #include <KUrl> //nuevo
  5.  
  6. #include "mainwindow.h"
  7.  
  8. int main (int argc, char *argv[])
  9. {
  10. KAboutData aboutData( "tutorial5", "tutorial5",
  11. ki18n("Tutorial 5"), "1.0",
  12. ki18n("A simple text area which can load and save."),
  13. KAboutData::License_GPL,
  14. ki18n("Copyright (c) 2007 Developer") );
  15. KCmdLineArgs::init( argc, argv, &aboutData );
  16.  
  17. KCmdLineOptions options; //nuevo
  18. options.add("+[file]", ki18n("Document to open")); //nuevo
  19. KCmdLineArgs::addCmdLineOptions(options); //nuevo
  20.  
  21. KApplication app;
  22.  
  23. MainWindow* window = new MainWindow();
  24. window->show();
  25.  
  26. KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); //nuevo
  27. if(args->count()) //nuevo
  28. {
  29. window->openFile(args->url(0).url()); //nuevo
  30. }
  31.  
  32. return app.exec();
  33. }

[edit] mainwindow.h

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <KXmlGuiWindow>
  5. #include <KTextEdit>
  6.  
  7. class MainWindow : public KXmlGuiWindow
  8. {
  9. Q_OBJECT
  10.  
  11. public:
  12. MainWindow(QWidget *parent=0);
  13. void openFile(const QString &inputFileName); //nuevo
  14.  
  15. private:
  16. KTextEdit* textArea;
  17. void setupActions();
  18. QString fileName;
  19.  
  20. private slots:
  21. void newFile();
  22. void openFile();
  23. void saveFile();
  24. void saveFileAs();
  25. void saveFileAs(const QString &outputFileName);
  26. };
  27.  
  28. #endif

[edit] mainwindow.cpp

  1. #include "mainwindow.h"
  2.  
  3. #include <KApplication>
  4. #include <KAction>
  5. #include <KLocale>
  6. #include <KActionCollection>
  7. #include <KStandardAction>
  8. #include <KFileDialog>
  9. #include <KMessageBox>
  10. #include <KIO/NetAccess>
  11. #include <KSaveFile>
  12. #include <QTextStream>
  13.  
  14. MainWindow::MainWindow(QWidget *parent)
  15. : KXmlGuiWindow(parent),
  16. fileName(QString())
  17. {
  18. textArea = new KTextEdit;
  19. setCentralWidget(textArea);
  20.  
  21. setupActions();
  22. }
  23.  
  24. void MainWindow::setupActions()
  25. {
  26. KAction* clearAction = new KAction(this);
  27. clearAction->setText(i18n("Limpiar"));
  28. clearAction->setIcon(KIcon("document-new"));
  29. clearAction->setShortcut(Qt::CTRL + Qt::Key_W);
  30. actionCollection()->addAction("limpiar", clearAction);
  31. connect(clearAction, SIGNAL(triggered(bool)),
  32. textArea, SLOT(clear()));
  33.  
  34. KStandardAction::quit(kapp, SLOT(quit()),
  35. actionCollection());
  36.  
  37. KStandardAction::open(this, SLOT(openFile()),
  38. actionCollection());
  39.  
  40. KStandardAction::save(this, SLOT(saveFile()),
  41. actionCollection());
  42.  
  43. KStandardAction::saveAs(this, SLOT(saveFileAs()),
  44. actionCollection());
  45.  
  46. KStandardAction::openNew(this, SLOT(newFile()),
  47. actionCollection());
  48.  
  49. setupGUI();
  50. }
  51.  
  52. void MainWindow::newFile()
  53. {
  54. fileName.clear();
  55. textArea->clear();
  56. }
  57.  
  58. void MainWindow::saveFileAs(const QString &outputFileName)
  59. {
  60. KSaveFile file(outputFileName);
  61. file.open();
  62.  
  63. QByteArray outputByteArray;
  64. outputByteArray.append(textArea->toPlainText());
  65. file.write(outputByteArray);
  66. file.finalize();
  67. file.close();
  68.  
  69. fileName = outputFileName;
  70. }
  71.  
  72. void MainWindow::saveFileAs()
  73. {
  74. saveFileAs(KFileDialog::getSaveFileName());
  75. }
  76.  
  77. void MainWindow::saveFile()
  78. {
  79. if(!fileName.isEmpty())
  80. {
  81. saveFileAs(fileName);
  82. }
  83. else
  84. {
  85. saveFileAs();
  86. }
  87. }
  88.  
  89. void MainWindow::openFile() //cambiado
  90. {
  91. openFile(KFileDialog::getOpenFileName());
  92. }
  93.  
  94. void MainWindow::openFile(const QString &inputFileName) //nuevo
  95. {
  96. QString tmpFile;
  97. if(KIO::NetAccess::download(inputFileName, tmpFile, this))
  98. {
  99. QFile file(tmpFile);
  100. file.open(QIODevice::ReadOnly);
  101. textArea->setPlainText(QTextStream(&file).readAll());
  102. fileName = inputFileName;
  103.  
  104. KIO::NetAccess::removeTempFile(tmpFile);
  105. }
  106. else
  107. {
  108. KMessageBox::error(this,
  109. KIO::NetAccess::lastErrorString());
  110. }
  111. }

[edit] tutorial5ui.rc

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <gui name="tutorial5"
  3. version="1"
  4. xmlns="http://www.kde.org/standards/kxmlgui/1.0"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://www.kde.org/standards/kxmlgui/1.0
  7. http://www.kde.org/standards/kxmlgui/1.0/kxmlgui.xsd" >
  8.  
  9. <MenuBar>
  10. <Menu name="file" >
  11. <Action name="limpiar" />
  12. </Menu>
  13. </MenuBar>
  14.  
  15. <ToolBar name="mainToolBar" >
  16. <text>Main Toolbar</text>
  17. <Action name="limpiar" />
  18. </ToolBar>
  19.  
  20. </gui>

Es idéntico al tutorialxui.rc de los dos tutoriales anteriores excepto que tutorialx ahora es tutorial5.

[edit] Explicación

[edit] mainwindow.h

Lo único que hemos añadido a partir del tutorial 4 es la función openFile que tiene como parámetro un QString.

void openFile(const QString &inputFileName);

[edit] mainwindow.cpp

No tenemos nuevo código, solo lo hemos reordenado. Todo lo de void openFile() se ha movido a void openFile(const QString &inputFileName) excepto la llamada a KFileDialog::getOpenFileName().

De esta manera, podemos llamar a openFile() si queremos mostrar un diálogo, o podemos llamar a openFile(QString) si ya conocemos el nombre del archivo.

[edit] main.cpp

Aqui es donde la clase KCmdLineArgs realiza todo el trabajo.

[edit] Make, Instalar y Ejecutar

[edit] CMakeLists.txt

  1. project(tutorial5)
  2.  
  3. find_package(KDE4 REQUIRED)
  4. include_directories( ${KDE4_INCLUDES} )
  5.  
  6. set(tutorial5_SRCS
  7. main.cpp
  8. mainwindow.cpp
  9. )
  10.  
  11. kde4_add_executable(tutorial5 ${tutorial5_SRCS})
  12.  
  13. target_link_libraries(tutorial5 ${KDE4_KDEUI_LIBS}
  14. ${KDE4_KIO_LIBS})
  15.  
  16. install(TARGETS tutorial5 DESTINATION ${BIN_INSTALL_DIR})
  17. install( FILES tutorial5ui.rc
  18. DESTINATION ${DATA_INSTALL_DIR}/tutorial5 )

Con este archivo, podemos construir y ejecutar este tutorial de la misma forma que los tutoriales 3 y 4. Para mas información, mira el tutorial 3.

mkdir build && cd build
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME
make install
$HOME/bin/tutorial5
Retrieved from "http://techbase.kde.org/Development/Tutorials/KCmdLineArgs_(es)"
Categories: Tutorial | C++

Navigation

  • Home
  • Help
  • Recent changes

Sections

  • Getting started
  • Development
  • Schedules
  • Policies
  • Contribute
  • Projects

Toolbox

  • What links here
  • Related changes
  • Special pages
  • Printable version
  • Permanent link

Personal tools

  • 38.107.191.96
  • Talk for this IP
  • Log in / create account
  • Login with OpenID
Creative Commons License SA 3.0 as well as the GNU Free Documentation License 1.2
KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal