Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Creating a Qt C++ Application

Note: This tutorial assumes that you have experience in writing basic Qt applications, using Qt Designer to design user interfaces and using the Qt Resource System.

This tutorial describes how to use Qt Creator to create a small Qt application, Text Finder. It is a simplified version of the QtUiTools Text Finder example.

Setting Up Your Environment

Qt Creator automatically detects whether the location of Qt is in your PATH variable. If you have installed several Qt versions, follow the instructions in Selecting the Qt version to set the Qt path.

Creating the Text Finder Project

Note: Create the project with the Help mode active so that you can follow these instructions while you work.

  1. Select File > New File or Project > Qt Application Project > Qt Gui Application > Choose.

    "New File or Project dialog"

    The Introduction and Project Location dialog opens.

    "Introduction and Project Location dialog"

  2. In the Name field, type TextFinder.
  3. In the Create in field, enter the path for the project files. For example, C:\Qt\examples, and then click Next.

    The Select Required Qt Versions dialog opens.

    "Select Required Qt Versions dialog"

  4. Click Next to use the Qt version set in the path in your project.

    The Class Information dialog opens.

    "Class Information dialog"

  5. In the Class Name field, type TextFinder as the class name.
  6. In the Base Class list, select QWidget as the base class type.

    Note: The Header File, Source File and Form File fields are automatically updated to match the name of the class.

  7. Click Next.

    The Project Management dialog opens.

    "Project Management dialog"

  8. Review the project settings, and click Finish to create the project.

The TextFinder project now contains the following files:

  • textfinder.h
  • textfinder.cpp
  • main.cpp
  • textfinder.ui
  • textfinder.pro

"TextFinder project contents"

The .h and .cpp files come with the necessary boiler plate code. The .pro file is complete.

Filling in the Missing Pieces

Begin by designing the user interface and then move on to filling in the missing code. Finally, add the find functionality.

Designing the User Interface

"Text Finder UI"

  1. In the Editor mode, double-click the textfinder.ui file in the Projects view to launch the integrated Qt Designer.
  2. Drag and drop the following widgets to the form:

    "Adding widgets to Text Finder UI"

  3. Double-click the Label widget and enter the text Keyword.
  4. Double-click the Push Button widget and enter the text Find.
  5. In the Properties pane, change the objectName to findButton.

    "Changing object names"

  6. Press Ctrl+A to select the widgets and click Lay out Horizontally (or press Ctrl+H) to apply a horizontal layout (QHBoxLayout).

    "Applying horizontal layout"

  7. Drag and drop a Text Edit widget (QTextEdit) to the form.
  8. Select the screen area and click Lay out Vertically (or press Ctr+V) to apply a vertical layout (QVBoxLayout).

    "Text Finder UI"

    Applying the horizontal and vertical layouts ensures that the application UI scales to different screen sizes.

  9. To call a find function when users press the Find button, you use the Qt signals and slots mechanism. A signal is emitted when a particular event occurs and a slot is a function that is called in response to a particular signal. Qt widgets have predefined signals and slots that you can use directly from Qt Designer. To add a slot for the find function:
    • Right-click the Find button to open a context-menu.
    • Select Go to Slot > clicked(), and then select OK.

      A private slot, on_findButton_clicked(), is added to the header file, textfinder.h and a private function, TextFinder::on_findButton_clicked(), is added to the source file, textfinder.cpp.

  10. Press Ctrl+S to save your changes.

For more information about designing forms with Qt Designer, see the Qt Designer Manual.

Completing the Header File

The textfinder.h file already has the necessary #includes, a constructor, a destructor, and the Ui object. You need to add a private function, loadTextFile(), to read and display the contents of the input text file in the QTextEdit.

  1. In the Projects view, double-click the textfinder.h file to open it for editing.
  2. Add a private function to the private section, after the Ui::TextFinder function, as illustrated by the following code snippet:
     private slots:
         void on_findButton_clicked();
    
     private:
         Ui::TextFinder *ui;
         void loadTextFile();

Completing the Source File

Now that the header file is complete, move on to the source file, textfinder.cpp.

  1. In the Projects view, double-click the textfinder.cpp file to open it for editing.
  2. Add code to load a text file using QFile, read it with QTextStream, and then display it on textEdit with setPlainText(). This is illustrated by the following code snippet:
     void TextFinder::loadTextFile()
     {
         QFile inputFile(":/input.txt");
         inputFile.open(QIODevice::ReadOnly);
    
         QTextStream in(&inputFile);
         QString line = in.readAll();
         inputFile.close();
    
         ui->textEdit->setPlainText(line);
         QTextCursor cursor = ui->textEdit->textCursor();
         cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor, 1);
     }
  3. To use QFile and QTextStream, add the following #includes to textfinder.cpp:
     #include <QtCore/QFile>
     #include <QtCore/QTextStream>
  4. For the on_findButton_clicked() slot, add code to extract the search string and use the find() function to look for the search string within the text file. This is illustrated by the following code snippet:
     void TextFinder::on_findButton_clicked()
     {
         QString searchString = ui->lineEdit->text();
         ui->textEdit->find(searchString, QTextDocument::FindWholeWords);
     }
  5. Once both of these functions are complete, add a line to call loadTextFile() in the constructor, as illustrated by the following code snippet:
     TextFinder::TextFinder(QWidget *parent)
         : QWidget(parent), ui(new Ui::TextFinder)
     {
         ui->setupUi(this);
         loadTextFile();
     }

The on_findButton_clicked() slot is called automatically in the uic generated ui_textfinder.h file by this line of code:

 QMetaObject::connectSlotsByName(TextFinder);

Creating a Resource File

You need a resource file (.qrc) within which you embed the input text file. The input file can be any .txt file with a paragraph of text. Create a text file called input.txt and store it in the textfinder folder.

To add a resource file:

  1. Select File > New File or Project > Qt > Qt Resource File > Choose.

    "New File or Project dialog"

    The Choose the Location dialog opens.

    "Choose the Location dialog"

  2. In the Name field, enter textfinder.
  3. In the Path field, enter C:\Qt\examples\TextFinder, and click Next.

    The Project Management dialog opens.

    "Project Management dialog"

  4. In the Add to project field, select TextFinder.pro and click Finish to open the file in the code editor.
  5. Select Add > Add Prefix.
  6. In the Prefix field, replace the default prefix with a slash (/).
  7. Select Add > Add Files, to locate and add input.txt.

    "Editing resource files"

Compiling and Running Your Program

Now that you have all the necessary files, click the button to compile your program.

X

rc="scripts/functions.js" type="text/javascript">
Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 64
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. La rubrique Qt a besoin de vous ! 1
Page suivante

Le Qt Developer Network au hasard

Logo

Comment fermer une application

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt qtcreator-2.0
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web