Archive:Development/Tutorials/KCmdLineArgs (zh TW): Difference between revisions

From KDE TechBase
(Created page with '{{Template:I18n/Language Navigation Bar|Development/Tutorials/KCmdLineArgs}} {{TutorialBrowser_(zh_TW)| series=初學者教學| name=命令列參數 (Under construction [[User...')
 
m (AnneW moved page Development/Tutorials/KCmdLineArgs (zh TW) to Archive:Development/Tutorials/KCmdLineArgs (zh TW) without leaving a redirect: Obsolete)
 
(8 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Template:I18n/Language Navigation Bar|Development/Tutorials/KCmdLineArgs}}
{{Template:I18n/Language Navigation Bar_(zh_TW)|Development/Tutorials/KCmdLineArgs}}


{{TutorialBrowser_(zh_TW)|
{{TutorialBrowser_(zh_TW)|
Line 11: Line 11:
next=[[Development/Tutorials/###|教學 6 - ###]] (TODO [[User:milliams]])|  
next=[[Development/Tutorials/###|教學 6 - ###]] (TODO [[User:milliams]])|  


reading={{class|KCmdLineArgs}} {{class|KCmdLineOptions}}
reading={{class|KCmdLineArgs}}{{class|KCmdLineOptions}}
}}
}}


==摘要==
==摘要==
 
現在我們有了一個可以載入和儲存檔案的文字編輯器。我們要讓這個編輯器像其他桌面程式一樣,能用命令列參數開啟檔案,甚至可以在 Dolphin 裡使用''開啟方式''來開啟檔案。
Now that we have a text editor which can open and save files. We will now make the editor act more like a desktop application by enabling it to open files from command line arguments or even using ''Open with'' from within Dolphin.


[[image:introtokdetutorial5.png|frame|center]]
[[image:introtokdetutorial5.png|frame|center]]
Line 23: Line 22:


===main.cpp===
===main.cpp===
<code cppqt n>
<syntaxhighlight lang="cpp-qt" line>
#include <KApplication>
#include <KApplication>
#include <KAboutData>
#include <KAboutData>
Line 40: Line 39:
   KCmdLineArgs::init( argc, argv, &aboutData );
   KCmdLineArgs::init( argc, argv, &aboutData );


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


   KApplication app;
   KApplication app;
Line 49: Line 48:
   window->show();
   window->show();


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


   return app.exec();
   return app.exec();
}
}
</code>
</syntaxhighlight>


===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 73: Line 72:
   public:
   public:
     MainWindow(QWidget *parent=0);
     MainWindow(QWidget *parent=0);
     void openFile(const QString &inputFileName); //new
     void openFile(const QString &inputFileName); //新增的
    
    
   private:
   private:
Line 89: Line 88:
   
   
#endif
#endif
</code>
</syntaxhighlight>


===mainwindow.cpp===
===mainwindow.cpp===
<code cppqt n>
<syntaxhighlight lang="cpp-qt" line>
#include "mainwindow.h"
#include "mainwindow.h"
   
   
Line 181: Line 180:
}
}
   
   
void MainWindow::openFile() //changed
void MainWindow::openFile() //變更
{
{
   openFile(KFileDialog::getOpenFileName());
   openFile(KFileDialog::getOpenFileName());
}
}


void MainWindow::openFile(const QString &inputFileName) //new
void MainWindow::openFile(const QString &inputFileName) //新增的
{
{
   QString tmpFile;
   QString tmpFile;
Line 205: Line 204:
   }
   }
}
}
</code>
</syntaxhighlight>


===tutorial5ui.rc===
===tutorial5ui.rc===
<code xml n>
<syntaxhighlight lang="xml" line>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<gui name="tutorial5"
<gui name="tutorial5"
Line 229: Line 228:


</gui>
</gui>
</code>
</syntaxhighlight>
This is identical to the <tt>tutorial''x''ui.rc</tt> from the last two tutorials except <tt>tutorial''x''</tt> is now <tt>tutorial5</tt>.
這和前兩個教學的 <tt>tutorial''x''ui.rc</tt> 一樣,唯一的改變就是從 <tt>tutorial''x''</tt> 變成了<tt>tutorial5</tt>


==解釋==
==解釋==
Line 236: Line 235:
===mainwindow.h===
===mainwindow.h===


Here we have done nothing but add a new <tt>openFile</tt> function which takes a <tt>QString</tt>
這裡我們只新增 <tt>openFile</tt> 函式,它接受一個 <tt>QString</tt> 作為參數。
<code cppqt>
<syntaxhighlight lang="cpp-qt">
void openFile(const QString &inputFileName);
void openFile(const QString &inputFileName);
</code>
</syntaxhighlight>


===mainwindow.cpp===
===mainwindow.cpp===


There's no new code here, only rearranging. Everything from <tt>void openFile()</tt> has been moved into <tt>void openFile(const QString &inputFileName)</tt> except the call to <tt>KFileDialog::getOpenFileName()</tt>.
這部分沒有新增程式碼,只是重新整理一下而已。所有 <tt>void openFile()</tt> 裡的東西都被移到了 <tt>void openFile(const QString &inputFileName)</tt> 裡,除了 <tt>KFileDialog::getOpenFileName()</tt> 的呼叫。


This way, we can call <tt>openFile()</tt> if we want to display a dialog, or we can call <tt>openFile(QString)</tt> if we know the name of the file already.
這樣,如果我們要一個對話框就呼叫 <tt>openFile()</tt>,如果已經有檔案名稱,呼叫<tt>openFile(QString)</tt> 就可以了。


===main.cpp===
===main.cpp===
Line 254: Line 253:


===CMakeLists.txt===
===CMakeLists.txt===
<code ini n>
<syntaxhighlight lang="make" line>
project(tutorial5)
project(tutorial5)
   
   
Line 273: Line 272:
install( FILES tutorial5ui.rc  
install( FILES tutorial5ui.rc  
         DESTINATION  ${DATA_INSTALL_DIR}/tutorial5 )
         DESTINATION  ${DATA_INSTALL_DIR}/tutorial5 )
</code>
</syntaxhighlight>


With this file, the tutorial can built and run in the same way as tutorial 3 and 4. For more information, see tutorial 3.
有了這個檔案,這個教學就可以像教學3和4一樣建構和執行了。更多資訊,請見教學3。


  mkdir build && cd build
  mkdir build && cd build

Latest revision as of 15:16, 23 June 2013

Template:I18n/Language Navigation Bar (zh TW)

Template:TutorialBrowser (zh TW)

摘要

現在我們有了一個可以載入和儲存檔案的文字編輯器。我們要讓這個編輯器像其他桌面程式一樣,能用命令列參數開啟檔案,甚至可以在 Dolphin 裡使用開啟方式來開啟檔案。

程式碼

main.cpp

#include <KApplication>
#include <KAboutData>
#include <KCmdLineArgs>
#include <KUrl> //new
 
#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; //新增的
  options.add("+[file]", ki18n("Document to open")); //新增的
  KCmdLineArgs::addCmdLineOptions(options); //新增的

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

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

  return app.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <KXmlGuiWindow>
#include <KTextEdit>
 
class MainWindow : public KXmlGuiWindow
{
  Q_OBJECT
  
  public:
    MainWindow(QWidget *parent=0);
    void openFile(const QString &inputFileName); //新增的
  
  private:
    KTextEdit* textArea;
    void setupActions();
    QString fileName;
 
  private slots:
    void newFile();
    void openFile();
    void saveFile();
    void saveFileAs();
    void saveFileAs(const QString &outputFileName);
};
 
#endif

mainwindow.cpp

#include "mainwindow.h"
 
#include <KApplication>
#include <KAction>
#include <KLocale>
#include <KActionCollection>
#include <KStandardAction>
#include <KFileDialog>
#include <KMessageBox>
#include <KIO/NetAccess>
#include <KSaveFile>
#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("Clear"));
  clearAction->setIcon(KIcon("document-new"));
  clearAction->setShortcut(Qt::CTRL + Qt::Key_W);
  actionCollection()->addAction("clear", 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() //變更
{
  openFile(KFileDialog::getOpenFileName());
}

void MainWindow::openFile(const QString &inputFileName) //新增的
{
  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"?>
<gui name="tutorial5"
     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="clear" />
    </Menu>
  </MenuBar>

  <ToolBar name="mainToolBar" >
    <text>Main Toolbar</text>
    <Action name="clear" />
  </ToolBar>

</gui>

這和前兩個教學的 tutorialxui.rc 一樣,唯一的改變就是從 tutorialx 變成了tutorial5

解釋

mainwindow.h

這裡我們只新增 openFile 函式,它接受一個 QString 作為參數。

void openFile(const QString &inputFileName);

mainwindow.cpp

這部分沒有新增程式碼,只是重新整理一下而已。所有 void openFile() 裡的東西都被移到了 void openFile(const QString &inputFileName) 裡,除了 KFileDialog::getOpenFileName() 的呼叫。

這樣,如果我們要一個對話框就呼叫 openFile(),如果已經有檔案名稱,呼叫openFile(QString) 就可以了。

main.cpp

This is where all the KCmdLineArgs magic happens.

編譯、安裝與執行

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 )

有了這個檔案,這個教學就可以像教學3和4一樣建構和執行了。更多資訊,請見教學3。

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

繼續前進

現在你可以開始學習下一課:### (TODO User:milliams) 教學。