Development/Tutorials/KCmdLineArgs (es): Difference between revisions

From KDE TechBase
(translation to spanish)
 
(translation to spanish)
Line 7: Line 7:
name=Argumentos para la linea de ordenes
name=Argumentos para la linea de ordenes


pre=[[Development/Tutorials/Saving and loading_(es)|Tutorial 4 - Cargar y Guardar]]|
pre=[[Development/Tutorials/Saving and loading|Tutorial 4 - Loading and saving]]|


next=[[Development/Tutorials/###|Tutorial 6 - ###]] (TODO [[User:milliams]])|  
next=[[Development/Tutorials/###|Tutorial 6 - ###]] (TODO [[User:milliams]])|  

Revision as of 01:13, 30 December 2008


Development/Tutorials/KCmdLineArgs


Argumentos para la linea de ordenes pre=Tutorial 4 - Loading and saving
Serie   Tutorial para principiantes
Requisitos previos   Ninguno
Siguiente   Tutorial 6 - ### (TODO User:milliams)
Lectura avanzada   KCmdLineArgs KCmdLineOptions

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.

El código

main.cpp

  1. include <KApplication>
  2. include <KAboutData>
  3. include <KCmdLineArgs>
  4. include <KUrl> //nuevo
  1. include "mainwindow.h"

int main (int argc, char *argv[]) { KAboutData aboutData( "tutorial5", "tutorial5", ki18n("Tutorial 5"), "1.0", ki18n("A simple text area which can load and save."), KAboutData::License_GPL, ki18n("Copyright (c) 2007 Developer") ); KCmdLineArgs::init( argc, argv, &aboutData );

KCmdLineOptions options; //nuevo options.add("+[file]", ki18n("Document to open")); //nuevo KCmdLineArgs::addCmdLineOptions(options); //nuevo

KApplication app;

MainWindow* window = new MainWindow(); window->show();

KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); //nuevo if(args->count()) //nuevo { window->openFile(args->url(0).url()); //nuevo }

return app.exec(); }

mainwindow.h

  1. ifndef MAINWINDOW_H
  2. define MAINWINDOW_H
  1. include <KXmlGuiWindow>
  2. include <KTextEdit>

class MainWindow : public KXmlGuiWindow { Q_OBJECT

public: MainWindow(QWidget *parent=0); void openFile(const QString &inputFileName); //nuevo

private: KTextEdit* textArea; void setupActions(); QString fileName;

private slots: void newFile(); void openFile(); void saveFile(); void saveFileAs(); void saveFileAs(const QString &outputFileName); };

  1. endif

mainwindow.cpp

  1. include "mainwindow.h"
  1. include <KApplication>
  2. include <KAction>
  3. include <KLocale>
  4. include <KActionCollection>
  5. include <KStandardAction>
  6. include <KFileDialog>
  7. include <KMessageBox>
  8. include <KIO/NetAccess>
  9. include <KSaveFile>
  10. include <QTextStream>

MainWindow::MainWindow(QWidget *parent) : KXmlGuiWindow(parent), fileName(QString()) { 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());

KStandardAction::open(this, SLOT(openFile()), actionCollection());

KStandardAction::save(this, SLOT(saveFile()), actionCollection());

KStandardAction::saveAs(this, SLOT(saveFileAs()), actionCollection());

KStandardAction::openNew(this, SLOT(newFile()), actionCollection());

setupGUI(); }

void MainWindow::newFile() { fileName.clear(); textArea->clear(); }

void MainWindow::saveFileAs(const QString &outputFileName) { KSaveFile file(outputFileName); file.open();

QByteArray outputByteArray; outputByteArray.append(textArea->toPlainText()); file.write(outputByteArray); file.finalize(); file.close();

fileName = outputFileName; }

void MainWindow::saveFileAs() { saveFileAs(KFileDialog::getSaveFileName()); }

void MainWindow::saveFile() { if(!fileName.isEmpty()) { saveFileAs(fileName); } else { saveFileAs(); } }

void MainWindow::openFile() //cambiado { openFile(KFileDialog::getOpenFileName()); }

void MainWindow::openFile(const QString &inputFileName) //nuevo { QString tmpFile; if(KIO::NetAccess::download(inputFileName, tmpFile, this)) { QFile file(tmpFile); file.open(QIODevice::ReadOnly); textArea->setPlainText(QTextStream(&file).readAll()); fileName = inputFileName;

KIO::NetAccess::removeTempFile(tmpFile); } else { KMessageBox::error(this, KIO::NetAccess::lastErrorString()); } }

tutorial5ui.rc

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"> <gui name="tutorial5" version="1">

 <ToolBar name="mainToolBar" >
   <text>Main Toolbar</text>
   <Action name="limpiar" />
 </ToolBar>
 <MenuBar>
   <Menu name="file" >
     <Action name="limpiar" />
   </Menu>
 </MenuBar>

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

Explicación

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);

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.

main.cpp

Aqui es donde la clase KCmdLineArgs realiza todo el trabajo.

Make, Instalar y Ejecutar

CMakeLists.txt

project(tutorial5)

find_package(KDE4 REQUIRED) include_directories( ${KDE4_INCLUDES} )

set(tutorial5_SRCS

 main.cpp
 mainwindow.cpp

)

kde4_add_executable(tutorial5 ${tutorial5_SRCS})

target_link_libraries(tutorial5 ${KDE4_KDEUI_LIBS}

                               ${KDE4_KIO_LIBS})

install(TARGETS tutorial5 DESTINATION ${BIN_INSTALL_DIR}) install( FILES tutorial5ui.rc

        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